0

There is a question posted on S.O. with the same title already, but I am stuck in a different part.

I am setting my state with:

  var index = this.state.rectangles.indexOf(eachRect);
  const newRects = [...this.state.rectangles];
  newRects[index].x = event.target.x();
  newRects[index].y = event.target.y();
  this.setState({ rectangles: newRects });

As far as I know, doing const newRects = [...this.state.rectangles] is creating a different object rather than pointing to the same reference (which was the other S.O question's mistake, and so there is a distinction between my prevState and this.state. However, logging the prevState and this.state in componentDidUpdate() still returns true.

I also tried setting state with:

  this.setState(prevState => {
                          console.log(prevState.rectangles[index]);
                          let oldRects = [...prevState.rectangles];
                          oldRects[index].x = event.target.x();
                          oldRects[index].y = event.target.y();
                          console.log("new rects: ", oldRects);
                          return { rectangles: oldRects };
                        });

also doesn't work.

Acy
  • 589
  • 2
  • 9
  • 25
  • Possible duplicate of [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – JJJ Jul 01 '19 at 18:44

1 Answers1

2

setState is not synchronous! If you want to make sure that the state is updated before logging it, just use the second argument, which provides a callback for whenever the state update finishes.

this.setState({item: newItem},() => console.log(this.state.item))
Dupocas
  • 20,285
  • 6
  • 38
  • 56