I have a handleClick() function which updates the state of a component.
handleClick = () => {
let temp_map = new Map();
temp_map.set('left', null);
temp_map.set('bottom',null);
temp_map.set('right', null);
temp_map.set('top', null);
var dots = Array(75).fill(temp_map);
// dots[24]['left'] = 23;
console.log(dots[23])
dots[24].set('left', 23);
dots[23].set('right', 24)
this.setState({dots: dots});
console.log(dots)
console.log(this.state.dots)
}
In the above code I have created an array of size 75 and fill them with a map with key value pairs.
dots[24].set('left', 23);
dots[23].set('right', 24);
And I do console.log(dots) I get the following:
How does all maps in the 75 locations of the dots array get their left keys updates?
And the after I call
this.setState({dots: dots});
and then do console.log(this.state.dots) I get the following:
why does not the state gets updated.
Any help is highly appreciated.
2
Answers
Short answer, setting the state and using its value in the same function might not work because it wouldn’t have updated yet.
After setting a value, use that value in a separate
useEffect
hook that depends on it.The state does get updated.
As Emiel already said,
setState
is asynchronous. This means that while your code continues to execute (in this case the twoconsole.log
) thesetState
operation hasn’t necessarily finished yet and because of that the unaltered state is being returned.The official docs explain this very thoroughly and you are being presented ways on how to handle your problem. For example using a callback (simple solution that is directly applicable in your case).
https://reactjs.org/docs/react-component.html#setstate
https://reactjs.org/docs/state-and-lifecycle.html