Acy
Acy

Reputation: 659

ReactJS componentDidUpdate() prevState equals to currentState

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.

Upvotes: 0

Views: 179

Answers (1)

Dupocas
Dupocas

Reputation: 21357

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))

Upvotes: 2

Related Questions