Redux: combReducers is shape independent

Trying to split my only reducer into different reducers combineReducers

is a handy redux function for this purpose. combineReducers

though restrict the state to a specific state with a reducer for at least every first level state key. So in some cases, you either need to add more required reducers or change the shape of your state.

To be more specific, let's say the app store looks like:

let store = {
    a: true,
    b: false,
    c: {...}
    d: {...}    
}

      

For the above store, I need to define a reducer for each of the above keys and combine them, so that it would be something like:

const reducerA = (state, action) => {...}
const reducerB = (state, action) => {...}
const reducerC = (state, action) => {...}
const reducerD = (state, action) => {...}

const rootReducer = combineReducers({
    a: reducerA,
    b: reducerB,
    c: reducerC,
    d: reducerD
});

      

I would like to keep reducerC

and reducerD

handle the corresponding objects in the state, but I need to have a common reducer for the keys a

and b

the state.

How can I add root level state key values ​​without defining those extra reducers reducerA

and reducerB

or adding a parent with a shared reducer reducerAB

? Is this possible with help combineReducers

or should I approach the desired behavior differently?

+3


source to share


1 answer


No, the intended use case for combineReducers

this is to decouple logic to support each slice of state, and delegate that work to separate functions. If you really want both a

and are b

managed by the same function instance, you either need to collect them into a chunk (for example state.ab.a

), or use something other than combineReducers

.



You can read the Structuring Reducers - BeyondcombineReducers

section in the Redux docs for a discussion of additional ways to organize reducer logic, as well as the Redux FAQ about sharing reducers .

+2


source







All Articles