![license](https://img.shields.io/github/license/mashape/apistatus.svg)
combine-reducers-global-state
A substitute for the default combineReducers function that comes with redux, aiming to solve the problem of cross-state access in local slice reducers. This combineReducers implementation passes globalState
as the third argument to reducers, making it available along with the local state slice.
globalState
here is the whole top-level state returned from store.getState()
before it is sliced inside the combineReducer
.
Usage
For example, given a store state at some point:
{
items: {
uid1: {
id: 'uid1',
name: 'item1'
},
uid2: {
id: 'uid2',
name: 'item2'
},
uid3: {
id: 'uid3',
name: 'item3'
}
},
display: ['uid2', 'uid3'],
editing: {
uid1: {
id: 'uid1',
name: 'renamed_item1'
}
}
}
Reducers that make use of global state may look like this:
const getAllIds = gState => Object.keys(gState);
export const displayReducer = (state = [], action, globalState) => {
switch (action.type) {
case 'ADD_ITEM':
return [...state, action.payload.id];
case 'REMOVE_ITEM':
return state.filter(id => id !== action.payload.id);
case 'ADD_ALL_ITEMS':
return getAllIds(globalState);
case 'REMOVE_ALL_ITEMS':
return [];
default:
return state;
}
};
const getItemById = (gState, id) => gState.items[id];
export const editingReducer = (state = {}, action, globalState) => {
switch (action.type) {
case 'START_EDIT_ITEM':
case 'RESET_EDIT_ITEM':
{
const { id } = action.payload;
return {
...state,
[id]: getItemById(globalState, id)
};
}
case 'EDIT_ITEM':
{
const { id, ...props } = action.payload;
return {
...state,
[id]: { ...state[id], ...props }
};
}
case 'SAVE_EDIT_ITEM':
case 'CANCEL_EDIT_ITEM':
return { ...state, [action.payload.id]: undefined };
default:
return state;
}
};
const getEditingItemById = (gState, id) => gState.editing[id];
export const itemsReducer = (state = {}, action, globalState) => {
switch (action.type) {
case 'SAVE_EDIT_ITEM':
{
const { id } = action.payload;
return {
...state,
[id]: { ...state[id], ...getEditingItemById(globalState, id) }
};
}
default:
return state;
}
};
If your selectors make time consuming calculations, it is recommended to use memoization, for example with the help of a third-party library such as reselect.
Finally, combineReducer
makes globalState
available to all reducers passed to it:
import { createStore } from 'redux';
import combineReducers from 'combine-reducers-global-state';
import * as reducers from './reducers';
const reducer = combineReducers(reducers);
const store = createStore(reducer);
...