0

Why am I getting this error?

relevant code:

this.state = {
    now: 0
}


setInterval(function () {
    this.setState({ now: this.state.now + 1});
}, 100);

I am trying to increment now in order to update a ProgressBar.

zanahorias
  • 140
  • 11
  • Possible duplicate of [Incrementing state value by one using React](https://stackoverflow.com/questions/42364838/incrementing-state-value-by-one-using-react) – pavi2410 Aug 03 '18 at 18:15
  • 1
    Execution context is different within the `setInterval` callback than where it was declared. You'll need to bind a function, create a closure, or use an arrow function. Have a look at [this question](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) for a little more information about execution context. – Fissure King Aug 03 '18 at 18:15
  • 1
    `setInterval(() => this.setState({ now: this.state.now + 1}), 100);` – Tholle Aug 03 '18 at 18:21
  • 1
    @Tholle that worked! If you want to submit as an answer, I'll accept it :) – zanahorias Aug 03 '18 at 18:38

2 Answers2

0

Your problem is that when you reference 'this' inside the function, this is the function itself not the context outside. If you are using ecmascript you can use an arrow function

this.state = {
    now: 0
}

setInterval(() =>{
    this.setState({ now: this.state.now + 1});
}, 100);

with an arrow function 'this' have a different meaning.

or you can create a reference outside your context, like this.

this.state = {
    now: 0
}

let self = this;

setInterval(function () {
    self.setState({ now: self.state.now + 1});
}, 100);
-1

Probably when interval function runs 'this' doesn't means the same as when setInteval was called

You might try something like this

this.state = {
    now: 0
}

let that = this 

setInterval(function () {
    that.setState({ now: that.state.now + 1});
}, 100);
Omar Alves
  • 723
  • 4
  • 13