3

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?

1 Answer 1

6

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.