React documentation states that ajax request should be initiated from componentDidMount
lifecycle event (see react docs) .
Why this event?
In most cases, when loading data using ajax, I want to display some kind of loading bar, e.g.:
componentDidMount() {
this.setState({isLoading: true});
fetch(...)
.then(...)
.then(() => this.setState({isLoading: false})
}
but this fires render
method 3 times (initial render immediatelly followed by setting isLoading = true
and then by isLoading = false
What's wrong about sending ajax request from componentWillMount
event?
Well, isLoading: true
could be part of the initial state, no need to set it after component did mount => only 2 renderings, not 3.
According to https://github.com/reactjs/react-redux/issues/210, the consequence of calling render
only once from componentWillMount
means that if setState
will be asynchronously called after render
, it won't have any effect (if I understand the comments correctly).
Not sure if there is a chance that the callback with setState
can execute before render
and thus no loading screen will be visible, only the results, thus sometimes it would "work" (most likely in DEV) but in reality it would be a race condition very hard to debug...
See also: https://reactjs.org/docs/faq-ajax.html
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