How to have combineReducers and custom reducers in Redux?

Viewed 327

Currently, all of my reducers only need the data from their value of the state, so my 'rootReducer' looks like this

export const appReducer = combineReducers({ foo: fooReducerFunction, bar: barReducerFunction})

which is fine, but now I have a reducer that needs other parts of the state, and I know it can be done like this

export function App(state: AppState, action: AppActions): AppState {
    return {
       foo: fooReducerFunction(state.foo, action),
       bar: fooReducerFunction(state.bar, action),
       baz: bazReducerFunction({foo: state.foo, bar: state.bar}, action)
    } 
}

but I don't want to have to write out all of the other reducers explicity like with foo and bar when only one piece of my store needs other parts of the store. Is there any way to combine custom reducers and combineReducers into something like this?

const appReducer = combineReducers({ foo: fooReducerFunction, bar: barReducerFunction})

export function App(state: AppState, action: AppActions): AppState {
    return {
       ...appReducer,
       baz: bazReducerFunction({foo: state.foo, bar: state.bar}, action)
    } 
}
1 Answers

It is possible to combine reducers in such a way, but a simpler solution to your problem is to grab a snapshot of the redux store in your action and pass the slice of state you need to your reducer upon dispatch. If you're using redux-thunk for example, the following pattern should work:

export const actionFoo = (data) =>  {
  return (dispatch, getState) => {
    // access slice of state first
    const { otherStateSlice } = getState()
    dispatch({ type: UPDATE_DATA, otherStateSlice, data })
  }
}
Related