ComponentDidMount() is triggered when the component is mounted, including when it is hydrated following server-side rendering.
One of the solutions I found online is checking whether we have data in the state; however this requires a lot of code to include on every component. What are other solutions?
componentDidMount() {
// if rendered initially, we already have data from the server
// but when navigated to in the client, we need to fetch
if (!this.state.data) {
this.constructor.fetchData(this.props.match).then(data => {
this.setState({ data })
})
}
}
I have found an alternative solution. In my Redux store I keep the URL of the current page. Therefore on navigation, I am able to do the following:
componentDidMount() {
const { url, match } = this.props;
if (url !== match.url) {
fetchData(match.path);
}
}
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