0

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 })
  }
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Rodrigo
  • 135
  • 4
  • 45
  • 107
  • You should do both changes in the same `setState`. I see really no reason not to since you're explicitly setting `logged` to true just before. – Emile Bergeron Feb 08 '21 at 14:42

1 Answers1

2

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

yovchokalev
  • 623
  • 7
  • 14