Search code examples
reduxredux-reducers

How to share state between 2 combine reducers?


I have 2 reducers that I use and combine them. In the first reducer, I have something that gets all the initial data (which is also relevant for the second reducer).

How do I use the data in the state that I initialize/set from the first reducer to the second one?

function reducer1(state = initialState, action = '') {
    switch (action.type) {
        case constants.INITIAL_DATA:

            returnstate.set('data', fromJS(document.data));

            ....

Then I combine both of those reducers and I want to access "data" from both of them (or pass the data as initialState to the second reducer).


Solution

  • A reducer should return a plain object and have no side effects. If you want the same state available in 2 different action.type cases, then they either need to be in the same function, or a parent function needs to pass the state to different reducer functions, like so:

    function parentReducer(state = {}, action = '') {
      switch (action.type) {
        case CASE_ONE:
          return childReducer1(state, action)
        case CASE_TWO:
          return childReducer2(state, action)
        default:
          return state
      }
    }
    

    But this brings up an important design point: each (top-level) reducer represents a distinct branch of the Redux state tree, and you can probably always design your data store in a way that different parts of the tree don't need to be shared. In Redux (check out the DevTools), you have a single object, and the top-level keys of this object are the names of your top-level reducer functions.

    Basically, if you perceive a need to set a different state in a reducer, so other reducers can use that, it evidence of a need to rethink the store's design.