Skip to content
Advertisement

React state not retuning the latest value of state

The value of this.state.topText and this.state.bottomText is always one change behind. E.g if I type 1234 in topText’s input box, the value of this.state.topText would be 123. The react docs say to fix asynchronous updates we should use the form of setState() that accepts a function rather than an object. I have done that and the value of setState is still lagging. How do I fix the setState() in handleChange()?

App.js

JavaScript

MemeGenerator.js

JavaScript

Advertisement

Answer

setState accepts a callback as a second param which will be executed right after the state change.

JavaScript

Please check the below:

https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296 https://upmostly.com/tutorials/how-to-use-the-setstate-callback-in-react

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