Why no setState in componentDidMount?
See original GitHub issueThis is less of an issue and more of a question on how you handle things.
React docs says to put ajax-requests in componentDidMount. But I would also like to cancel the request in componentWillUnmount as that data is not needed if the component isn’t there. And to do so, I need a reference to the promise created in componentDidMount. I thought to achieve this by putting it on state, like so:
componentDidMount() {
this.setState({ serverRequest: this.props.fetcData() });
}
componentWillUnmount() {
const { serverRequest } = this.state;
if (serverRequest.isPending()) serverRequest.cancel();
}
(This is using bluebird btw, not native promises)
And this works, but the linter complains about the setState-call in componentDidMount.
I tracked down the issue where the rule was added (#345 & #346), and while the OP states that it follows your style guide, I can’t find any reference to that rule in your docs.
So, my question is: Do you have any other way of keeping around references to async stuff created in componentDidMount such as ajax-requests, setTimeouts etc to be able to clean them up in componentWillUnmount? Or should I just disable the rule for that particular line?
Issue Analytics
- State:
- Created 8 years ago
- Reactions:42
- Comments:35 (5 by maintainers)

Top Related StackOverflow Question
Why not put the
setStatecall incomponentWillMount? That would be the inverse ofcomponentWillUnmountAs the docs state that they belong in
componentDidMount: