function ProductItem(props) {
var addedToCart = false
const valuesCart = {
val1 : "Add to cart",
val2 : "Added to cart"
}
const [changedText , setText] = useState(props.type)
const [changedBtnText , setBtnText] = useState(valuesCart.val1)
const clickHandler = () => {
console.log(addedToCart)
if(!addedToCart){
setText(valuesCart.val2)
setBtnText(valuesCart.val2)
}
else{
setText(props.type)
setBtnText(valuesCart.val1)
}
addedToCart = !addedToCart
console.log(addedToCart)
}
Here I am Initializing addedToCart variable to check whether item is already added to cart
var addedToCart = false
The clickHandler function is triggered by onClick event.
const clickHandler = () => {
This is used for debugging puposes
console.log(addedToCart)
This checks if the addedToCart variable is false and sets the values of item type and button label to "Added To Cart"
if(!addedToCart){
setText(valuesCart.val2)
setBtnText(valuesCart.val2)
}
The else loop should trigger when the addedToCart variable is True and then it will set the item type and button label back to there initial values before the first click.
else{
setText(props.type)
setBtnText(valuesCart.val1)
}
addedToCart = !addedToCart
This is used for debugging purposes
console.log(addedToCart)
}
This is what the output on console looks like when I am clicking the Add To Cart button for 3 times
[After the First click The outputs are (false, true) which is as expected but after the second click the output should be (true, false) whereas it is coming the same (false, true) and after the 3rd click the output is the required output i.e. (truem false)][1] [1]: https://i.stack.imgur.com/12pH1.png
The false and true indicate the value of addedToCart variable.
Help me solve this issue and get the button to behave as a toggle switch which can alter is value with a single click.