So I have a React component that fetches data upon componentDidMount()
. That component route may take a query string to determine which resource to load (i.e. the id of the resource, /some/where?resource=123
.
When I change the id in the query string and press ENTER in the browser, the component is not remounted, but stay as it is. So the data for, say, resource 654 is not loaded.
To fix that, I could copy and paste the code for the componentDidMount into componentDidUpdate()
and fetch the data again if the query string has changed.
Code Sample
componentDidMount() {
const { resource } = this.props.location.query;
if (resource) {
this.fetchData();
// where fetch data is a function that makes calls
// to an API and updates the Redux state
}
}
componentDidUpdate(prevProps, prevState) {
const { resource } = this.props.location.query;
if (resource && resource !== prevProps.location.query.resource) {
this.fetchData();
}
}
But is there a better way to handle this?
React router suggests this exact thing from their docs: Component Lifecycle
If you look closer to the bottom there is an example of data fetching for the component.
I personally really like fetching data this way. It keeps data fetching tied to the React lifecycle so you can always be sure of when the data fetching happens.
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