David Normington David Normington - 1 year ago 178
React JSX Question

Recommended approach to deep linking using redux and react-router

I am building a web app using React (15.3.0), Redux (3.5.2) and react-router (2.6.1). I include the versions as I've seen a few related posts but they reference old versions of these libraries.

I have some state that I would like to persist on the URL so that the user can deep link to it. By deep linking, I mean that a user can link directly to a state of a page. I have various pages in my app, each page has a separate reducer, the state for each page should persist between pages.

I've read Dan Abramov's recommended approach: How to sync Redux state and url hash tag params
Which seems ok, apart from persisting state between pages.

An example scenario:

  1. User lands on page one:

  2. User interacts with the page causing state to be saved in the URL:

  3. User goes to page 2:

  4. User interacts with page 2:

  5. User links to page 1, expecting to see that page as they left it. Problem! How do we recover the state from page 1?

I've looked at react-router-redux, but I can't tell if it does what I need it to?

Is there a common approach to this problem? If so what is it? If not, can you suggest an approach?

Answer Source

I'm sure there is more than one answer to this; you just need to pick one and implement it.

If it were me, I would do this:

  1. Use the redux store as the single source of truth for state
  2. Subscribe to the store in some way (perhaps a redux middleware) and update the url params when the relevant state for page1 changes
  3. If a user visits /page1, use the stored state (I'm assuming state will need to be synced to a server to be able to store/recover it).
  4. If a user visits /page1?state={...}, either a) merge the URL state into the stored/recovered state or b) skip recovering and use the URL directly.

I would even go further and NOT sync the state to the url, since that seems like wasted effort (unless users are relying on bookmarking a page). Just render a React component saying "Share this URL" and have it render a URL with proper query params.

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