I am sorry in advance if I am asking riddiculus question but I am little stuck with combining reducers.
I have a component with counter reducer that modifies state passed to it. I would want to create another reducer with additional action handlers and add it to the store allowing it to modify exactly the same properties of the store.
So just for the sake of the example I do it as shown in very naive example below.
Is there a way to run second reducer on the same dataset from different part of the application?
function counter(state = 0, action) {
// ... actions: INCREMENT, DECREMENT
return state;
}
function reseter(state = 0, action) {
// ... actions: RESET
return state;
}
let reducers = (state, action) => {
return reseter(counter(state, action), action)
}
I tried to use combineReducers passing array as a parameter but looking at the tests it seems only functions are accepted. Digging around I start to think that this kind of attempt is a little foolish.
I have no issues assigning reducers to two different store properties but what should I do If I would want to add additional reducer to store property that already has reducer assigned.
A few thoughts. First, this is a usage question, and should really be asked on Stack Overflow instead. You'll get more attention over there.
Second, it's entirely possible to run multiple reducer functions in a row. There's a useful utility called https://github.com/acdlite/reduce-reducers that does that, or you can write your own. combineReducers is just a utility for the most common use case.
Third, I'm working on a new set of pages for the Redux docs on the topic of "Structuring Reducers", which you may be interested in. It tries to help answer this kind of question. The current WIP pages are at https://github.com/markerikson/redux/blob/structuring-reducers-page/docs/recipes/StructuringReducers.md .
Thank you very much @markerikson.
let reducers = reduceReducers(counter, reseter)
Sweet!
I've got this short function from a friendly project:
export default function queueReducers(...reducers) {
return (state, action) => reducers.reduce((s, reducer) => reducer(s, action), state);
}
Usage is pretty simple
export const rootReducer = combineReducers({
yourNamespace: queueReducers(
reducer1,
reducer2
)
});
Most helpful comment
Sweet!