I am confused with how setState works.
Here is a portion of my code:
handleBarsChange(value) {
this.setState({numberOfbars: value});
this.resetArray();
}
apparently, when the resetArray() function executes and tries to access the this.state.numberOfbars state variable, setState hasn't updated the value yet.
I want some explanation on how and where should the setState be executed and when can i expect to see the change.
Thank you!
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.
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();
});
}