lalezky
lalezky

Reputation: 554

Is it correct to use await setState()?

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

Answers (6)

Alex S
Alex S

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

S. Hesam
S. Hesam

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

David Schumann
David Schumann

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

stackoverfloweth
stackoverfloweth

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

Dan Inactive
Dan Inactive

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

Anas
Anas

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

Related Questions