Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent componentDidMount from fetching data if already available from server-side

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 })
      })
    }
  }
like image 991
Kevin Farrugia Avatar asked Dec 05 '25 04:12

Kevin Farrugia


1 Answers

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);
  }
}
like image 153
Kevin Farrugia Avatar answered Dec 06 '25 19:12

Kevin Farrugia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!