Reputation: 29
How I can get the incremented variable in the same setState?
I have the following example
https://codesandbox.io/s/jjj3k80o3y
As you can see the first is incremented correctly but the second is behind with one value. It is possible for incrementedIndex to be the same value as currentIndex?
incrementAction = () => {
this.setState({
currentIndex: this.state.currentIndex + 1,
incrementedIndex: this.state.currentIndex
});
};
Upvotes: 0
Views: 26
Reputation: 3725
React setStates
are batched. It doesn't update the state one property at a time, in sequence.
In the second property you are still using the old version of the state, that's why it does not increment.
BTW, when you use the current value of the state to compute the next one, you should use the method notation, not the object one:
incrementAction = () => {
this.setState(prevState => ({
currentIndex: prevState.currentIndex + 1,
incrementedIndex: prevState.currentIndex
}));
};
Upvotes: 2