I couldn't find an answer to this anywhere...
I'm trying to use setState to update the state of my app but, I need to call an async
function after setState
is finished.
Can I await
an async
function inside the callback for setState
?
setState({foo: bar}, async () => {await doStuff()});
Also assuming that this works, can I rely on setState
finishing before doStuff
is called, and can I rely on doStuff
being await
ed?
Yes, indeed you can. The special thing about async functions is that they always return Promises, so especially for functions whose return value is not important (callbacks, for example), you can safely put in an async function, and it would work as expected.
Taking this one step further, you can even have an async function as your componentDidMount
or componentWillReceiveProps
for example (but still not render
, which expects a JSX element to be returned, not a Promise).
The callback of the setState only fires when the state is updated so doStaff will not execute until state is updated. You can define the callback as async function and await inside it as any other function.
const setStateAsync = (newState) => {
return new Promise((resolve) => {
setState(newState, resolve);
});
you can use it like this Ex:
async componentDidMount() {
await setStateAsync(newState);
await doStuff()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With