-3

I have this function, I want console.log the output to show the state of isOpen, the expected output must be 'true' only.

open = () => {
    this.setState({
        isOpen: true
    })
}
Vipin Yadav
  • 1,616
  • 1
  • 14
  • 23
alioua walid
  • 247
  • 3
  • 19
  • Possible duplicate of [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Emile Bergeron Aug 19 '19 at 14:49

3 Answers3

3

Since the setState() is async, you need to call a callback, which executes after the state gets updates.

open = () => {
    this.setState({
        isOpen: true
     }, () => console.log(this.state.isOpen))
}
Nagesh
  • 437
  • 3
  • 13
0

this.setState will take a callback function.

open = () => {
this.setState({
    isOpen: true
 }, () => {
   console.log(this.state.isOpen ? this.state.isOpen : '')
 }
}
GRS
  • 1,829
  • 1
  • 9
  • 23
0

Since setState() is async, you need to put console.log in callback of setState.

    open = () => {
    this.setState({
        isOpen: true
     }, ()=> {
      console.log(this.state.isOpen);
    }
vipulp
  • 196
  • 9