-1

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.

Yuseff
  • 169
  • 4
  • 14
  • 2
    All of the items in the array are references to the same `Map` object. You should create a `new Map` for each item in the array. `setState` is asynchronous. That means that when you log it, it might not have been updated yet. Use lifecycle hooks to log changes in states. – Emiel Zuurbier Feb 21 '23 at 10:16
  • thank you for the help. I just could not figure out that the maps are being passed as references to the array using the fill method. so now I am using a loop to iterate over the array and filling the array with map. – Yuseff Feb 22 '23 at 06:49

2 Answers2

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])
Neelansh Mathur
  • 516
  • 1
  • 5
  • 10
0

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

OZOBPIR
  • 56
  • 3