State boolean returns true?

Hey,
I’m currently working on the Pomodoro challenge but now I’ve gotten stuck when trying to change a boolean (session) in the state.

According to another thread on the forum this should work:

  toggleStatus = () => { 
    this.setState({
      session: !this.state.session
    });
    console.log(this.state.session); 
  }

The boolean starts as true and when I run the method it should return false, but still returns true.

When I edit the code to “this.state.session: !this.state.session” it seems to work but I get an error stating “this is a reserved word” so that’s not an ideal solution :stuck_out_tongue:

full code can be viewed here: https://codepen.io/MarijkeBroos/pen/XoMdaY?editors=0011

1 Like

setState is asynchronous, so your console.log(this.state.session) will probably output the value of this.state.session before setState changes session. If you really want to output what this.state.session is after setState executes, you can put it into setState’s optional callback function to see the value.

  toggleStatus = () => { //session starts as true
    this.setState({
      session: !this.state.session
    }, () => {
      console.log('this.state.session after setState');
      console.log(this.state.session);
    });
    
  }
4 Likes

setState is asynchronous…

1 Like

Thanks for the replies, I wasn’t expecting setState to operate like this (it collects setStage callbacks in batches and then executes it?), but I’m glad that I got this learning moment still in the early stages of the project XD

At the moment session switches to false at least before I reset the timer, but would it be recommended to use a boolean in the state if changes constantly? (asking for other continuously changing variables as well)

1 Like

Not sure if this gonna be of any help but i was doing simple react timer app where i found out that you could use “prevState” in setState callback, which could be useful in cases with frequent state changes.

incTime() {
    this.setState(prevState => ({
      timerTime: prevState.timerTime + 1,
    }));
  }

So you could do some checking if prevState is what you want it to be or something like that.