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)
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)
Share Improve this question asked Jul 26, 2017 at 23:34 AdamGAdamG 2,6303 gold badges25 silver badges39 bronze badges1 Answer
Reset to default 12The 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);
});