Gilbert Nwaiwu
Gilbert Nwaiwu

Reputation: 728

redux: nested reducer access another store section

I use redux's combineReducers() helper function to combine two reducers like so:

const rootReducer = combineReducers({
  user: userReducer,
  accounts: accountsReducer
})

I know each reducer can only modify a slice of the store it's assigned to, "user" and "accounts" in this case.

How can i modify the "user" part of my store from my accounts reducer?

Upvotes: 2

Views: 164

Answers (1)

T Mitchell
T Mitchell

Reputation: 1017

You can't.

You can either listen to the same action in both reducers, or if you need to update the user state based on the update to the accounts' state, then you can use Redux thunks - https://github.com/gaearon/redux-thunk

const action = () => (dispatch, getState) => {
  // dispatch action that accounts reducer listens to
  dispatch({
    type: 'SOME_ACTION'
  })

  // get the new accounts state
  let { accounts } = getState()

  // dispatch action that user reducer listens to, passing the new accounts state
  dispatch({
    type: 'ANOTHER_ACTION',
    payload: {
      accounts
    }
  })
}

// call with
dispatch(action())

Upvotes: 3

Related Questions