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, orforceUpdatewith 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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With