-1

From what I read so far is that setState is ran asynchronously and so you wait and it first the callback method right after. Currently, it does not fire the callback at all. I have a button so far that when clicked it runs the triggerTimer function and I want it so that I change the state of isRunning to true and fire the callback method to start the timer

class App extends Component{
 constructor(prop){
    super(prop)
    this.state={
        isRunning: false,
        countdown: 0,
        pauses: 0
    };

    this.triggerTimer = this.triggerTimer.bind(this)
    this.startTimer = this.startTimer.bind(this)
    this.pauseTimer = this.pauseTimer.bind(this)
  }


triggerTimer(){
    console.log("i got hit")
    console.log("isRunning: " + this.state.isRunning)
    var isRunning = this.state.isRunning
    if(isRunning === false){
      this.setState=({
        isRunning: !isRunning,
      },function() {
        console.log("isRunningNow:" + this.state.isRunning)
        this.startTimer()
      });
      
      
      
    }else{
      this.setState={
        isRunning: !isRunning,
        countdown: 0,
        pauses:0
      }
      console.log("interupt and reset timer")
    }
  }
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
axesspwns
  • 113
  • 2
  • 14

1 Answers1

3

The problem seems to be a typo that is a valid javascript but not a valid react call.

When you do this.setState you cant use = right after it otherwise you are giving setState a new value.

So see this:

this.setState=({
             ^ REMOVE IT
  isRunning: !isRunning,
},function() {
  console.log("isRunningNow:" + this.state.isRunning)
  this.startTimer()
});
this.setState={
             ^ REMOVE IT AND WRAP THE OBJECT BETWEEN "(" and ")"
        isRunning: !isRunning,
        countdown: 0,
        pauses:0
      }

Some useful resources:

Marlom
  • 578
  • 5
  • 15