Search code examples
reactjsreduxreact-router-redux

How to load object from route parameter using redux


I'm using react-router-redux and I have a route like this

<Route path="/user/:userId" components={{ body: UserMaintenance }} />

Whats the recommended way to load user object corresponding to the userId parameter in the route?

My thoughts (I'm new to react & redux) would be to use the userId parameter in the UserMaintenance componentWillReceiveProps method and dispatch a FETCH_USER action to the store which will load into state.currentUser. The UserMaintenance component would then update when the currentUser parameter is updated as a result of the action.


Solution

  • First you must decide if you want your URL to be the source of truth for the userId (I'd suggest so).

    Then you know that whenever the URL/route changes, and at no other time, you will dispatch FETCH_USER.

    To change user from elsewhere within the app you just browserHistory.push('/user/1234') and know that the change in URL will trigger an update to the store.

    If you're happy with that, just dispatch the action in the route:

    <Route
      path="/user/:userId"
      components={{ body: UserMaintenance }}
      onEnter={state => {
        store.dispatch({
          type: ACTIONS.FETCH_USER,
          key: state.params.userId,
        });
      }}
    />
    

    If you're following this logic, you might not need react-router-redux.

    Interesting comments from the author of redux over here.