-2

This maybe a repetitive question but I am still not able to figure out why setState is not able to toggle boolean values? Here are the functions:

constructor(props){
    super(props)
    this.state = {
        isPlaying: false
    }
}

playButtonClicked = () => {
    this.setState((prevState) => ({
        isPlaying: !prevState.isPlaying
    }))
    console.log("updating state....state is="+this.isPlaying)  // Its printing undefined
    this.togglePlayPause();
}

Here's the div:

<button id="play-pause" onClick={this.playButtonClicked}></button>

Please let me know if you find the mistake. Thanks in advance.

Siddharth Shankar
  • 489
  • 1
  • 10
  • 21
  • 1
    this.state.isPlaying should go in console.log. Also, console log may not show your latest state. So, use callback of setstate. – Ajeet Shah May 17 '20 at 00:11
  • 1
    First off, this.isPlaying that you are trying to log, is invalid. It would this.state.isPlaying, also setState is asynchronous, it will be not be updated when you try to log it. – Alexander Staroselsky May 17 '20 at 00:11
  • 3
    Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Bassem May 17 '20 at 01:30

1 Answers1

3
 this.setState((prevState) => ({
        isPlaying: !prevState.isPlaying
    }), function() {
   console.log("updating state....state is="+this.state.isPlaying) 
  });

Setstate is async give console log in a callback.

Hadi Pawar
  • 1,090
  • 1
  • 11
  • 23