AdamG
AdamG

Reputation: 2630

SetState callback not waiting for state to update

Acording to the setState documentation the callback should fire after the new state has been set. However, my code

console.log(school);
this.setState({ lastSegment: school },console.log(this.state.lastSegment));

Prints:

Middle
Grammar

Since school="Middle" why is the setState callback printing "Grammar" (which is the previous value of this.state.lastSegment)

Upvotes: 1

Views: 1737

Answers (1)

Andy Ray
Andy Ray

Reputation: 32066

The callback is a function passed to another function as an argument and sometimes referred as anonymous function which means a function without a name, so you're executing the console.log in place, and returning the value as the second argument to setState. You want to pass in a function, not the result of console.log.

this.setState({ lastSegment: school }, () => { 
  console.log(this.state.lastSegment); 
});

or using ES5 syntax:

this.setState({ lastSegment: school }, function() { 
  console.log(this.state.lastSegment); 
});

Upvotes: 12

Related Questions