This.setState to setTimeout in react

Function to update the state:

animate() {
 setInterval(function(){
   setTimeout( this.setState({
     a: '123'
   }), 1000);
 }, 4000);
}

      

Method:

componentDidMount() {
  this.animate();
}

      

Mistake:

Uncaught TypeError: this.setState is not a function

      

Then the following code tried:

animate() {
 setInterval(function(){
   setTimeout( () => {this.setState({
     a: '123'
   })}, 1000);
 }, 4000);
}

      

And the following error:

Uncaught TypeError: _this2.setState is not a function

      

+3


source to share


2 answers


The problem stems from your definition setInterval

.

When you execute setInterval(function() {...})

, the keyword is this

no longer bound to the React component, but to the function that it calls internally, due to the introduction of the new scope.

You can switch it to:



animate() {
  const self = this

  setInterval(function() {
    setTimeout(() => self.setState({ a: '123' }), 1000)
  }, 4000)
}

      

This is self

how the value of the React component is assigned this

before the new scope is introduced, or you can use all arrow functions to store the keyword this

referencing the component:

animate() {
  setInterval(() => {
    setTimeout(() => this.setState({ a: '123' }), 1000)
  }, 4000)
}

      

+2


source


While the answer provided by m_callens is correct, I will add this capability using bind

as well for those using JavaScript pre-ES6.



animate() {
    setInterval((function(){
        setTimeout((function() {this.setState({
            a: '123'
        })}).bind(this), 1000);
    }).bind(this), 4000);
}

      

0


source







All Articles