Tuomas Toivonen Tuomas Toivonen - 1 year ago 65
Ajax Question

React, best way to deal with fetching when navigating between routes containing same component

Basically, I would like to fetch the latest data every time user navigates to different tab. For example, I have summary page and details page for customers, which both includes the same customers container component. I'm doing my initial fetching in

function, which doesn't get triggered in route change, as component stays in the DOM. Component necessarily doesn't receive new props either.

One solution would be to customize router link with fetch action being dispatched based on the href, but I'm pretty sure this is an anti-pattern, as it complicates code a lot, is hard to maintain, mixes concerns, and may result in a double fetch if target route didn't contain the component already.

Does React provide any lifecycle hook or mechanism that allow me to fetch in response to navigation event alone?

I'm using React-router-component and Redux.

Answer Source

As far as I understand both tabs happen to contain the same component and so React re-uses the DOM and doesn't create a new component instance, right?

You can use React's special key prop to force React to replace a specific instance.


<div className="tab-content>
  <div key="tab-1" className="shared-component-across-tabs">

And in the second tab you'd use key="tab-2".

Otherwise your route handler component will receive props.location.pathname from the router. You can also implement componentWillReceiveProps and check if the pathname has changed and re-fetch the data in that case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download