Search code examples
reduxreact-router-redux

Handle generic API call in different reducers


I have an entity called client and another one called person. client has a personId for it's main person and we also have a list of people that relates to this client in some way. Something like the following:

client: {
  clientId: 1
  personId: 1
  people: [{personId: 2}, {personId: 3}]
}

Suppose we have an action called REQUEST_PERSON, which dispatches RECEIVE_PERSON when finished, and two routes within react-router-redux, client/:clientId/ and client/:clientId/people/:personId that need to fetch the person info..

I have two reducers, one for the first route and the other for the second one. If I listen to RECEIVE_PERSON in both of them, they will always update their state, even when the action was not meant for them.

Should I have two different actions for each situation, like REQUEST_CLIENT_PERSON/RECEIVE_CLIENT_PERSON and REQUEST_PERSON/RECEIVE_PERSON that will call the same API route? Can I somehow avoid this duplication?


Solution

  • Short answer: yes, you should have two different actions. Having two different reducers listen for the same action type is very rarely something you want to do. I say rarely because there might be a case, but I've never run into one.

    The longer answer involves how to do that without repeating yourself. If you find that your reducers and actions are doing the same things and you've duplicated all the code, it would be worth setting up a higher order reducer as explained in the redux documentation.