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:
// example of a working state // a mapped stock of items items: uid1: id: 'uid1' name: 'item1' // ... uid2: id: 'uid2' name: 'item2' // ... uid3: id: 'uid3' name: 'item3' // ... // items on display display: 'uid2' 'uid3' // currently editing editing: uid1: id: 'uid1' name: 'renamed_item1' // ...
Reducers that make use of global state may look like this:
// reducers.js // selector that returns all item idsconst getAllIds = Object; // controls which items are currently on displayconst displayReducer = { }; // selector that returns one item with given idconst getItemById = gStateitemsid; // edits properties of an individual itemconst editingReducer = { }; // selector that returns an item being edited with given idconst getEditingItemById = gStateeditingid; // controls items stockconst itemsReducer = { };
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:
;;; const reducer = ; const store = ; ...