Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setTimeout in setState callbacks

Tags:

reactjs

I have the following code in a react component:

  calcTime: function() {
    time = <some time dependant value>
    this.setState({
      total_time: time
    }, window.setTimeout(this.calcTime, 1000));
  }

This works fine, except that while it's running I see the following exception in the console:

Uncaught Error: Invariant Violation: enqueueCallback(...): You called setProps, replaceProps, setState, replaceState, or forceUpdate with a callback that isn't callable.

I did think initially that this was down to having the setTimeout function there, so I extracted that out to another function and just added that as the callback method. However, when doing this, render stopped showing the updates to the DOM.

How should I do this correctly?

like image 296
Neil Middleton Avatar asked Apr 02 '26 07:04

Neil Middleton


1 Answers

Second argument in setState should be function., window.setTimeout returns number but not reference to function

var App = React.createClass({
  getInitialState: function () {
    return {
      total_time: 0
    }
  },
  
  componentDidMount: function () {
    this.calcTime();
  },
  
  calcTime: function() {
    var time = this.state.total_time + 10;
    
    this.setState({
      total_time: time
    }, () => { 
      window.setTimeout(this.calcTime, 1000)
    });
  },
  
  render: function() {
    return <div>{this.state.total_time}</div>;
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
like image 123
Oleksandr T. Avatar answered Apr 03 '26 23:04

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!