Is it correct to use await setState()?
Solution 1
No this.setState
doesn't return a promise.
So you can't use await in this case. You need to use the callback.
Solution 2
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 });
Solution 3
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).
Related videos on Youtube
lalezky
Updated on June 04, 2022Comments
-
lalezky about 2 years
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);
-
kumar k almost 6 yearsNo. It's not right way to use await in front of
setstate
function. If you want do async operation, don it in separate thread and using the callback function update thesetstate
function. -
anshu purohit almost 6 years
-
-
J.Ko over 5 yearsaccording to MDN, await expression can be used for "a Promise or any value to wait for. " developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
Anas over 5 yearsawait doesn't work with a callback. You can test it.
-
J.Ko over 5 yearsaccording to MDN, await expression can be used for "a Promise or any value to wait for. " developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
user2161301 over 5 yearsYep, that's what I meant in the first sentence of my answer :-)
-
Dhaval Patel over 5 years@Anas await is working fine please check here next.plnkr.co/edit/…
-
DillonHarless almost 3 yearsDon't know how this doesn't have more upvotes. Is this not advised or something? Working perfectly for me.
-
David Schumann over 2 yearsBecause callbacks are ugly
-
famfamfam about 2 yearsany hook solution?
-
Danial Ahmed about 2 years@famfamfam try useEffect hook. stackoverflow.com/questions/56247433/…