Reputation: 443
I have used setInterval to fetch the data which will be invoked every 30secs. Below is the snippet of that.
this.interval = setInterval(() => this.props.fetchEvents().catch((err) => {
this.setState({ isLoadingFailed: true });
}), 30000);
Now i am implementing sorting functionality in which my component will be re-rendered when i click sort button. So when my component is re-rendered i am trying to destroy the call sent for fetching the data by implementing 'componentWillUnmount' but it is not working and my sorting is done only after data is fetched.
componentWillUnmount() {
clearInterval(this.interval);
}
Sorting:
changeSortOrder() {
if (this.state.inAsc == -1) {
this.state.inAsc = 1;
} else {
this.state.inAsc = -1;
}
}
Sorting button html:
{
this.state.group == 'admin' && this.state.inAsc == -1
? <Tooltip content="Click to Sort" position={Position.BOTTOM}>
<span className="event-main-navigation-element" onClick={this.changeSortOrder.bind(this)}>
<SortAsc className="event-main-navigation-icon" />
</span>
</Tooltip>
: this.state.group == 'admin' && this.state.inAsc == 1
? <Tooltip content="Click to Sort" position={Position.BOTTOM}>
<span className="event-main-navigation-element" onClick={this.changeSortOrder.bind(this)}>
<SortDesc className="event-main-navigation-icon" />
</span>
</Tooltip> : <div />
}
Can someone let me know how i can destroy the call?
Upvotes: 0
Views: 130
Reputation: 957
componentWillUnmount()
is only called when a component is removed from the DOM, as mentioned in the docs:
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.
So your clearInterval()
is not called on clicking the button. You could clear the interval in the changeSortOrder()
call.
On a side-note:
Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead. (see constructor docs)
Upvotes: 1