Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router: changing query string does not re-mount the component

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?

like image 337
nbkhope Avatar asked Feb 17 '17 18:02

nbkhope


1 Answers

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.

like image 172
Special Character Avatar answered Nov 14 '22 16:11

Special Character