What's the problem on this function? Why I can't check for a variable state after set a value?
const updateHandler = () => {
this.setState({ logged: true })
if (this.state.logged) {
this.setState({ showDialog: true })
}
}
What's the problem on this function? Why I can't check for a variable state after set a value?
const updateHandler = () => {
this.setState({ logged: true })
if (this.state.logged) {
this.setState({ showDialog: true })
}
}
this.setState is async, so it is not guaranteed that you have the new state in the next line. To do that you need to write the code as a callback to setState:
this.setState({
logged: true
}, () => {
if (this.state.logged){
this.setState({ showDialog: true })
}
})
But there is no reason to use it, because in that case logged will always be true.
A good reason to use it is when you have a complicated shouldComponentUpdate. In that case it is useful to see what you have after setting the state