Reputation: 554
my function looks like this:
this.setState(prevState => ({
time : prevState.time + 1
}), function() {
doSomethingWithNewState(this.state.time)
})
is it correct to use await in this situation? like this:
await this.setState(prevState => ({
time : prevState.time + 1
}));
doSomethingWithNewState(this.state.time);
Upvotes: 32
Views: 63673
Reputation: 81
As David says, that promisedSetState function works great.
One thing to keep in mind, if you are destructuring your state in your function, do not use the destructured state as it is a const and won't change.
myFunction = () => {
const { someState } = this.state;
await promisedSetState({someState: someValue });
console.log(someState) <<<--- will be old value
console.log(this.state.someState) <<<--- will be new value
}
Upvotes: 2
Reputation: 6753
Definitely not. You can pass a callback to the setState
like this:
this.setState(prevState => ({
time : prevState.time + 1
}),
() => doSomethingWithNewState(this.state.time));
Upvotes: 3
Reputation: 14813
You can't await this.setState
for the reasons already stated. But you can write your own awaitable setState function easily:
promisedSetState = (newState) => new Promise(resolve => this.setState(newState, resolve));
now you can call
await promisedSetState({ someState: true });
Upvotes: 41
Reputation: 6917
setState
takes a callback? Not sure why the first example would be an issue
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
Upvotes: -1
Reputation: 10070
As the previous answer mentioned, setState()
does not return a Promise, so you cannot use it with await
as you intend. (Although you can await
synchronous code as well).
When it's said that setState()
is asynchronous, what's meant is that the effect of setState()
may happen at a later time.
Furthermore, while reading this.state
in the callback function will give you the state of the component at that particular moment in time when the callback gets executed, it's not exactly what you'd expect, because all callback functions are called after a batch of setState()
calls gets executed. (See this issue).
Upvotes: 5
Reputation: 5727
No this.setState
doesn't return a promise.
So you can't use await in this case. You need to use the callback.
Upvotes: 23