I may be missing something. I know setState
is asynchronous in React, but I still seem to have this question.
Imagine following is a handler when user clicks any of the buttons on my app
1. ButtonHandler()
2. {
3. if(!this.state.flag)
4. {
5. alert("flag is false");
6. }
7. this.setState({flag:true});
8.
9. }
- Now imagine user very quickly clicks first one button then second.
- Imagine the first time the handler got called
this.setState({flag:true})
was executed, but when second time the handler got called, the change to the state from the previous call has not been reflected yet -- andthis.state.flag
returnedfalse
. - Can such situation occur (even theoretically)? What are the ways to ensure I am reading most up to date state?
- I know
setState(function(prevState, props){..})
gives you access to previous state but what if I want to only read state like on line 3 and not set it?