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
In Redux official document there's a chapter called 'Beyond combineReducers'. It mentioned about Sharing data between slice reducers.
https://redux.js.org/recipes/structuring-reducers/beyond-combinereducers#sharing-data-between-slice-reducers
I personally prefer the third solution mentioned in the link, which is adding a third customized reducer to handle the "special" cases where data needs to be shared across slices, then use reduce-reducers to combine the new customized reducer and the original combined reducer (i.e. appReducer + inventoryReducer).
const crossSliceReducer = (state, action) => {
if (action.type === 'CROSS_SLICE_ACTION') {
// You can access both app and inventory states here
}
return state;
}
// Combine the reducers like you did before
const combinedReducer({app: appReducer, inventory: inventoryReducer});
// Add the cross-slice reducer to the root reducer
const rootReducer = reduceReducers(combinedReducer, crossSliceReducer)
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));
};
}