In my React app, my appReducer manages global stuff such as notifications, user info, etc.
One of the modules in the app is the inventory module which has its own reduce
Following up with what @azium said, as far as I understand, in Redux each reducer is allocated a slice of the entire state object and their operations are restricted in that slice. They are not allowed to access the state slice managed by any other reducer, and they shouldn't do that.
The concept description of Redux is that it is a predictable state container. But when I look at what we are trying to achieve in this question, if we were to access/modify state managed by another reducer-B in our reducer-A, the predictability and maintainability of the app is compromised according to me.
Without compromising on anything or moving undesired logic into our components, we can achieve what we need.
Inside appReducer
you create a type SET_INVENTORY
which does what DISPLAY_NOTIFICATION
does. You can have multiple subscriptions for the single action that dispatches type SET_INVENTORY
(in appReducer and inventoryReducer).
As shown below, in appReducer, if the action type is either SET_INVENTORY
or DISPLAY_NOTIFICATION
, the reducer updates the key displayNotification
.
export default (state = initialState, action) => {
switch (action.type) {
case types.SET_INVENTORY :
case types.DISPLAY_NOTIFICATION :
return Object.assign({}, state, {
displayNotification: action.value
})
default: return state
}
}
Create a method that couples the dispatching of two actions,
let's say you have an action
function setInventory(inventoryItem) {
return {
type: types.SET_INVENTORY,
inventoryItem
};
}
and another action
function displayNotification(value) {
return {
type: types.DISPLAY_NOTIFICATION,
value,
};
}
create a thunk to couple them:
export function notifyAndSetInventory(notify, inventoryItem) {
return dispatch => {
dispatch(displayNotification(notify));
return dispatch(setInventory(inventoryItem));
};
}