You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There is always a scenario that when data is being fetched from the server, the browser needs to display a spin icon. With react + redux, you may probably implement it in such way:
class SampleComponent extends React.Component {
componentDidMount() {
// dispatch the action here to fetch new data from the server and update the store
}
render() {
if (// data is empty) { // or use conditional rendering
return(<renderSpin />);
}
return (<renderWithData />);
}
}
The implementation looks good at the first glance. However, the data may be incorrect in a case:
SampleComponent mounts for the first time and the store is updated, where everything is fine.
SampleComponent umounts.
SampleComponent mounts for the second time and the fetching data is failed or takes a long time. The spin will be skipped because the data is not empty, but it is the data fetched from the first mount and is old.
We can see an unexpected behavior.
To avoid such problem, there could be 2 solutions.
destroy the data in componentWillUnmount:
class SampleComponent extends React.Component {
componentDidMount() {
// dispatch the action here to fetch new data from the server and update the store
}
componentWillUnmount() {
// dispatch the action here to make the data in the store empty
}
render() {
if (// data is empty) {
return(<renderSpin />);
}
return (<renderWithData />);
}
}
This method is only applicable in the case that this data is not used in other components or you are confident that destroying the data upon umounting of this component is ok.
But if the data is not used in other components, why not use state instead of redux for this data?
dispatch an empty data before fetching from the server in the action:
There is always a scenario that when data is being fetched from the server, the browser needs to display a spin icon. With react + redux, you may probably implement it in such way:
The implementation looks good at the first glance. However, the data may be incorrect in a case:
We can see an unexpected behavior.
To avoid such problem, there could be 2 solutions.
componentWillUnmount
:This method is only applicable in the case that this data is not used in other components or you are confident that destroying the data upon umounting of this component is ok.
But if the data is not used in other components, why not use
state
instead of redux for this data?This method is applicable for most cases, but it will dispatch twice in each data updating.
Comment on this issue if you have other ideas.
The text was updated successfully, but these errors were encountered: