Use a function as the first parameter to setState
Add a callback to setState to determine when the state is up to date
this.state = { counter: 1 };
this.setState({
counter: this.state.counter + 1
});
this.setState({
counter: this.state.counter + 1
});
Object.assign({},
{counter: this.state.counter + 1},
{counter: this.state.counter + 1},
{counter: this.state.counter + 1},
);
this.setState({
counter: this.state.counter + 1
});
this.setState((prevState, props) => {
return {
counter: prevState.counter + 1
};
});
this.setState({name: "Tim"});
// Won't be updated yet
console.log(this.state.name);
this.setState({name: "Tim"}, () => {
console.log(
"Now state is up to date",
this.state.name
);
});