This page of React's docs shows that async requested data should be consumed in the componentDidMount
event, while getInitialState
initialize the state object to a default empty state.
Is there a reason for that? Maybe getInitialState is not expected to do this or has a different purpose? Is it due to some internal logic of the library?
Note to moderators and answerers: this isn't an opinion-based question: if a reason exists, that would be the answer, however, a good, correct answer to my question could be as well "No, there isn't any particular reason, do whatever you feel better"
getInitialState
should be a pure function of props (though they often aren't used). In other words, with the same props getInitialState should return the same data.
componentDidMount
is allowed to have dynamic behavior, and cause side effects such as dom manipulation and ajax requests (that's the main intention of it).
A common way to handle this is with an early return of either an empty div, loading message, <div>Loading</div>
), or loading indicator (e.g. spinkit).
On first render the spinner will be shown, and then eventually state is updated with data and the main part of render can be run.
render: function(){
// while loading
if (!this.state.data){
return <div className="spinner"></div>
}
// loaded, you can use this.state.data here
return <div>...</div>
}
You wouldn't want to do this because your component will be waiting on the async request and it won't be able to mount until it's finished. If you have html with a couple state variables, let react render first instead of making it wait. I know this is an opinion but it's also a separation of concerns thing as well.
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