I am confused with how setState works.
Here some code (I am working on a sorting visualiser)
handleBarsChange(value){
this.setState({numberOfbars: value});
this.resetArray();
}
apparently, when resetArray() function executes and tries to access the numberOfbars state variable, its still the old value.
I want some explanation on how and where should the setState be executed and when can i expect to see the change.
And please don't give me react documentation links, I tried ; but it did not resolve my doubts.
Thank you!
CodePudding user response:
setState
is asynchronous. It has a second callback argument that can be used to run code after a state transition. This isn't always the best approach, but with the very narrow example provided, it's hard to say.
this.setState({numberOfBars: value}, () => { this.resetArray() })
From the react docs:
The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.
https://reactjs.org/docs/react-component.html#setstate
CodePudding user response:
The fact is that setState()
function is async so even if you run code after you call it, some state may not be updated yet.
The solution is implement a callback when the state was updated succesfully (setState(<state>, <callback>)
), for example:
handleBarsChange(value){
this.setState({numberOfbars: value}, () => {
this.resetArray();
});
}