skip to Main Content

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:
enter image description here

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: enter image description here

why does not the state gets updated.
Any help is highly appreciated.

2

Answers


  1. 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.

    useEffect(() => {
       console.log(dots);
    }, [dots])
    
    Login or Signup to reply.
  2. 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 two console.log) the setState 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search