Why no setState in componentDidMount?
This 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?
Why not put the setState call in componentWillMount? That would be the inverse of componentWillUnmount
As the docs state that they belong in componentDidMount:
If you want to integrate with other JavaScript frameworks, set timers using
setTimeoutorsetInterval, or send AJAX requests, perform those operations in this method.
Touché :-) according to https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md, "Updating the state after a component mount will trigger a second render() call and can lead to property/layout thrashing."
However, since setState uses ===, i'm not sure if it's the best place to put a promise. What about an instance property?
Just go this.serverRequest = ...?
Sure. You'll want to make sure it's managed in the appropriate places, in case props change and whatnot, but otherwise that seems like it would be fine.
Assigning to this works perfectly, and it is indeed buggy to use state. Thanks for the help!
Ref facebook/react#5870
@SimenB Can you elaborate on this.serverRequest = ...?
@ericgrosse you can see the full example in the React docs: https://facebook.github.io/react/tips/initial-ajax.html Anything beyond that?
I lost "this" inside of componentDidMount() where I ran a Stomp (ActiveMQ) topic listener. Inside that listener "this" became undefined. An uneducated trick that worked was to save "this" into a variable "thus" before entering that listener and I could use it inside the message handler doing stuff such as "thus.forceUpdate()" and similar.
@mobimation or you could use an arrow function, and just use this directly
Thanks @ljharb will try
@SimenB I don't understand either! The eslint-plugin-react says
Prevent usage of setState in componentDidMount (no-did-mount-set-state).
Anyone can explain?
Doing setState in componentDidMount will cause a visible render flash.
However, when doing server-rendering, anything that requires a browser environment must go in componentDidMount, since that runs client-only, but componentWillMount runs on both client and server.
This is an OK rule to disable.
If this is an OK rule to disable, is the benefit really worth the inconvenience of the overrides? I would not consider it a general "best practice" to not use setState in componentDidMount.
If you have problematic render flashes you can work around that with various methods, and these methods often will not include moving setState from componentDidMount, but another fix, leaving you with a fix as well as the eslint-disable.
There is also a scene that you must change your state depending on the what dom looks like. As a result, you must detect the dom element after mounting, which means you have to write the this.setState in componentDidMount.
I don't think this rule should be enabled by default. As the docs state:
Calling setState() in this method will trigger an extra rendering, but it is guaranteed to flush during the same tick. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state.
So it causes no visible side-effects.
Use this pattern with caution because it often causes performance issues.
This could justify configuring it as a warning, but certainly not as an error.
It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
And it can be necessary.
It's definitely necessary for server rendering; I'm going to reopen this and change the default.
I've spent so long time because I have 'this.setState' on componentDidMount. It didn't work so I moved it to componentWillMount and now it's working.
I don't think that this rule makes any sense when using async/await.
Is there another, smarter way to do this?
async componentDidMount() {
try {
const response = await wpQuery();
const { headers, posts } = response;
this.setState({
posts,
maxPages: headers['x-wp-totalpages'],
maxPosts: headers['x-wp-total'],
});
} catch (error) {
this.setState({
error: 'Things went wrong, and the logic for error handling is irrelevant',
});
}
}
}
If it were a synchronous function, I'd understand a warning, and I'd probably want to see that warning.