Prasanna
Prasanna

Reputation: 4636

Merging reducer as a key in another reducer

I have a reducer reducerA that looks like this

reducerA = {
  A: [],
  B: {},
  C: {},
  D: [],
};

I have another reducer reducerB that looks like this

reducerB = {
  E: {},
}

What I would like to do is merge reducerB into reducerA and obtain something that would look something like this

reducerA = {
  A: [],
  B: {},
  C: {},
  D: [],
  reducerB: {
    E: {}
  },
};

Where changes to state variables A,B,C and D are triggered in reducerA function and changes in state variable E is still triggered in reducerB function.

I have already tried using combineReducers. But apparently, it combines reducerA and reducerB as children of a outer reducer. And that would require me to access the state variable inside reducerA as reducerA.reducerA.A

export default {
  reducerA: combinedReducers({reducerA, reducerB})
}

I would like to know if there is a rather clinical solution to the problem. I found quite a few libraries that do solve the problem. But I am still reluctant about them and would like to solve this without them if possible.

Upvotes: 1

Views: 359

Answers (2)

Susth
Susth

Reputation: 264

const reducerA = (state, action) => {
  const newState = {}
  switch (action.type) {
    case someaction:
      newState = {
        A: [],
        B: {},
        C: {},
        D: [],
      }
    default:
      newState = {
        ...state
      }
  }
  return {
    ...newState,
    reducerB: reducerB(state, action)
  }
}

This should solve your problem. ;D

Upvotes: 2

lipp
lipp

Reputation: 5926

I think what you ask for is against the redux reducer concept and breaks encapsulation. If you want to create a reducer which relays on state of reducerA and reducerB, you should probably dispatch the actions which are dispatched be reducerA and reducerB respectively and don't rely on other reducers.

Anyhow, when you are using react-redux, I'd recommend to employ mapDispatchToProps where you can create a mapping of the global state for your component props, e.g:

const mapStateToProps = state => {
  return state.reducerA.foo + state.reducerB.bar
}

connect(mapStateToProps)(YourComponent)

Upvotes: 0

Related Questions