-1

I wonder if there's any established pattern of having a reducer that can be re-used in different branches of the same global Redux state?

Typical example would be pagination. Every table grid has same params, like: data, pageNumber, pageSize, sortBy, sortOrder, filters, etc. It doesn't make sense to have a separate reducer (and set of corresponding actions as well) for every page that has grid in it. There should be a way to have just one and be able to re-use it wherever required.

jayarjo
  • 16,124
  • 24
  • 94
  • 138
  • I'm not sure what you're looking for. What you are describing sounds like what Redux was designed for. Is this what you are looking for: https://codesandbox.io/s/lm57klz7z?file=/src/App.js? If not, please provide some example code of your problem. – Shamar Yarde Dec 17 '20 at 11:13
  • From what I see your example has all products pre-fetched and hits the backend only with search keyword. I'm talking about the case when you fetch only data specific to a certain page and offset. So you actually need to send all params to the backend and you need to keep them all in redux state. – jayarjo Dec 17 '20 at 11:47

2 Answers2

1

Where I work we've created a fragment concept. For example, we have a searchFragment, which have actions to filter data. In this case, we've created the following actions:

  • createSearchFragmentActions: Responsible to create a set of actions with a prefix sent as an argument.
  • createSearchFragmentReducer: Responsible to create a sub-reducer with the name sent as an argument and deal with the actions dispatched.
  • createSearchFragmentSelectors: If you use reselect, this function basically returns a set of selectors to filter the subreducer created.
Renan Bandeira
  • 3,238
  • 17
  • 27
  • That's exactly what I implemented (with prefix and even naming of function almost exactly like that :D), but I thought it's kind of clunky, so was looking if there's a better way. Also I didn't manage to typesafe it properly in TypeScript. Did you? – jayarjo Dec 17 '20 at 11:49
  • No =/ We implemented this without having TypeScript – Renan Bandeira Dec 17 '20 at 15:00
1

Yes, this is a standard Redux pattern known as a "higher-order reducer".

markerikson
  • 63,178
  • 10
  • 141
  • 157