I've written a test case in Codepen
Run the test by clicking the button, then see the result from Browser Console.
You can see from the console log that even I called setState
multiple times before await
, it will only update the component once.
But if I call setState
multiple times after await
, it will update the component multiple times too.
Any idea why is this happening?
Code:
/*
* A simple React component
*/
class Application extends React.Component {
state = {
value: 0
}
onClickHandler = (e) => {
this.runAsyncFunc();
}
runAsyncFunc = async() => {
console.log('BEFORE AWAIT');
this.setState({ value: 1 });
this.setState({ value: 1 });
this.setState({ value: 1 });
await setTimeout(()=>{}, 2000);
console.log('AFTER AWAIT');
this.setState({ value: 1 });
this.setState({ value: 1 });
this.setState({ value: 1 });
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('updated');
}
render() {
return <div>
<p>{this.state.value}</p>
<button onClick={this.onClickHandler}>RUN TEST</button>
<p>Please check from Browser Console's Log</p>
</div>;
}
}
/*
* Render the above component into the div#app
*/
React.render(<Application />, document.getElementById('app'));