3

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).

David
  • 1,284
  • 1
  • 11
  • 21
  • Can you explain your use case? Normally, I would say that this is a sign that you have logic in your reducers that doesn't belong there. If you have state that depends on other state, it probably belongs in a container component instead. – James Brierley Mar 15 '16 at 16:51
  • one of the reducers just happen to pull the initial data - you could say its some kind of "parent" reducer - but at the end i combine them both. – David Mar 15 '16 at 16:56

1 Answers1

3

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.

pfkurtz
  • 494
  • 3
  • 7
  • I end up injecting each of the reducer with the relevant document.data.X - but your answer is very good and ill probably use it down the road - so Thanks! – David Mar 17 '16 at 07:42