Skip to content
Advertisement

React useState causes if-else to work incorrectly

So I am trying to set a value using a useState hook (React JS) in an if-else conditional statement.

I need to check whether there is addOnName (which is passed as a parameter), in the addOnContainer array and if it does, I need to deduct the addOnPrice (which is also passed as a parameter) to the totalprice using the setTotalPrice (useState hook).

If the addOnContainer does not include the addOnName, I have to add the addOnPrice to the totalprice.

The code works fine, as it gives me correct outputs in the chrome console. But when I try to use the useState hook to set total price, only the if block runs, and the else never runs no matter what the condition is.

I have tried moving the useState out of the if-else, and had no luck with that.

What am I doing wrong here? Note that this function is set to be executed when a checkbox is clicked.

JavaScript

Advertisement

Answer

At each rerender, let addOnContainer = []; is getting reset to empty array.

You can use a useRef to avoid it:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement