I have been using async await with babel in my ReactJS project. I discovered a convenient use with React setState that I would just like to understand better. Consider this code:
handleChange = (e) => {
this.setState({[e.target.name]: e.target.value})
console.log('synchronous code')
}
changeAndValidate = async (e) => {
await this.handleChange(e)
console.log('asynchronous validation code')
}
componentDidUpdate() {
console.log('updated component')
}
My intention was for the asynchronous validation code to run after the component has updated. And it works! The resulting console log shows:
synchronous code
updated component
asynchronous validation code
The validation code will only run after handleChange has updated the state and the new state is rendered.
Usually to run code after state has updated, you would have to use a callback after this.setState. Which means if you want to run anything after handleChange, you have to give it a callback parameter which is then passed to setState. Not pretty. But in the code example, somehow await knows that handleChange is complete after the state has updated... But I thought await only works with promises and waits for a promise to resolve before continuing. Theres no promise and no resolution in handleChange... How does it know what to wait for??
The implication seems to be that setState is run asynchronously and await is somehow aware of when it completes. Maybe setState uses promises internally?
Versions:
react: "^15.4.2"
babel-core: "^6.26.0"
babel-preset-env: "^1.6.0",
babel-preset-react: "^6.24.1",
babel-preset-stage-0: "^6.24.1"
babel-plugin-system-import-transformer: "^3.1.0",
babel-plugin-transform-decorators-legacy: "^1.3.4",
babel-plugin-transform-runtime: "^6.23.0"
await
onundefined
(becausehandleChange
doesn't return anything). Are you sure it is having an effect onsetState
? – Davin Tryonawait this.setState({ data: true }, () => console.log('callback')); console.log('inline');
clearly sayscallback
will be fired first, however - remove await and works as usually setState suppose to work -inline
first and thencallback
– Vlad