Skip to content
Advertisement

Function variable value resetting after calling this.setState

I am relatively new to the JavaScript world, i am learning react and have encountered a weird issue see this code

JavaScript

here i am concerned with the newPrice variable which is used update the state when more items are added, which works fine

problem is after the this.setState return the newPrice gets retested to 0 again so i can’t use it for the function at the bottom.

Yes i can use the state variable directly but due to the asnyc nature of setState execution i wanted to pass the variable value instead.

in the console you can see that first the outer console log gets executed then the inside one due to async nature of setState

enter image description here

maybe i am not getting some lifecycle react has that is generating this type of behavior.

here is the state values, in the values shouldn’t matter but still for a better picture

JavaScript

Any hint helps, thanks for reading.

Advertisement

Answer

this.setState() gets called asynchronously so you cannot rely on this.state referencing the updated value immediately after calling this.setState(). Have a read through the FAQ on component state.

If you want to reference the updated value of newPrice after the state has been updated, you can:

  1. Use the componentDidUpdate() lifecycle method. See https://reactjs.org/docs/react-component.html#componentdidupdate.
JavaScript
  1. Use the 2nd argument to this.setState(). See the docs at https://reactjs.org/docs/react-component.html#setstate.
JavaScript
  1. Use ReactDOM.flushSync(). See https://github.com/reactwg/react-18/discussions/21.
JavaScript

If I were to write this method, I would recommend using the componentDidUpdate lifecycle method as this will ensure updatePurchaseable is always called when the total price changes. If you only call updatePurchaseable inside your event handler, then you may end up with a bug if the price changes outside of that handler.

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