Tevon Strand-Brown
Tevon Strand-Brown

Reputation: 1738

How does react update state?

I'm getting a very strange issue that I don't know how to address.

I've got a fairly straightforward method: When a button is pressed it called toggleInverted()

toggleInverted() {
  if(this.state.inverted){
    this.setState({inverted: false});
  } else{
    console.log("got to else...");
    this.setState({inverted: true});
    console.log(this.state.inverted);
  }
}

The inverted field is initialized in the constructor to false. However the first time I click the button when I load the page, it doesn't correctly reset the state. The output is: got to else... false.

So somehow it is getting into this else statement, executing the setState, and yet not setting inverted to be true...

Is there something about setState that I am missing?

Upvotes: 0

Views: 71

Answers (2)

Pineda
Pineda

Reputation: 7593

setState may be asynchronous

Meaning you cannot expect the values of this.state to change immediately after setState is called.

To quote the docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value...


As an aside, you can figure your code by using the negative expression of the current inverted value as follows:

toggleInverted() {
  this.setState({inverted: !this.state.inverted});
}

Upvotes: 1

sukwonchoi
sukwonchoi

Reputation: 158

setState does not change your components state immediately. Your state change may be asynchronous and thus no guarantee that your console.log statement will print the changed state. setState however does always lead to the render method being called, so if you console log your state inside the render method of your component, your state should be true.

Also, this.setState({inverted: !this.state.inverted}) is a shorter version of your code snippit

Upvotes: 1

Related Questions