ClearInterval not working in reactjs
SetInterval works fine, but clearInterval doesn't work
See my code, I have a parent class Channel and Child Body, in the body, when the componentDidMount is called, then I set theInterval for the refreshState function. In the refreshState function I am trying to clear the Interval which does not work
var Header = require('../../common/header.jsx');
var Sidebar = require('../../common/sidebar.jsx');
var Footer = require('../../common/footer.jsx');
var Body = React.createClass({
componentDidMount: function() {
this.intervalId = setInterval(this.refreshStats, 1000);
},
componentWillUnmount: function(){
clearInterval(this.intervalId);
},
refreshStats: function() {
console.log(this.intervalId);
clearInterval(this.intervalId);
},
render: function() {
return (
<Container id='body'>
<Grid>
<Row>
<Col sm={12}>
<PanelContainer>
<Panel>
<PanelBody>
Test
</PanelBody>
</Panel>
</PanelContainer>
</Col>
</Row>
</Grid>
</Container>
);
}
});
var Channel = React.createClass({
mixins: [SidebarMixin, State],
render: function() {
var classes = React.addons.classSet({
'container-open': this.state.open
});
return (
<Container id='container' className={classes}>
<Sidebar />
<Header />
<Body />
<Footer />
</Container>
);
}
});
module.exports = Channel;
source to share
Another way is to save it directly to this
:
var Body = React.createClass({
componentDidMount: function() {
this.intervalId = setInterval(this.refreshStats, 1000);
},
componentWillUnmount: function(){
clearInterval(this.intervalId);
},
refreshStats: function() {
console.log(this.intervalId);
clearInterval(this.intervalId);
},
render: function() {
...
}
});
It takes fewer lines of code to do this, but it seems a little less clean. I myself keep it on state
, as the accepted answer suggests , but I post it in case someone more knowledgeable can comment on which method is more idiomatic.
Note also that when using React Timer, you don't have to worry about clearing unmount - this is about whether you save intervalId
to state
or from this
.
source to share
To store a descriptor on intervalId
, you need to store it in state
:
var Body = React.createClass({
getInitialState = function() {
return {};
},
componentDidMount: function() {
intervalId = setInterval(this.refreshStats, 1000);
this.setState({intervalId: intervalId});
},
componentWillUnmount: function(){
clearInterval(this.state.intervalId);
},
refreshStats: function() {
console.log(this.state.intervalId);
clearInterval(this.state.intervalId);
},
render: function() {
...
}
});
Otherwise it will not survive the render cycle.
source to share