You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Create global state selectors from local redux slice selectors.Inredux each of the slices is autonomous and the final store structure is defined by how the individual slices are merged withcombineReducers.createGlobalStateSelector takes local slice selectors and the slice structure to return global state selectors.
Install
npm i create-global-state-selector
Uses
The example below usesredux-toolkit however you can usecreateGlobalStateSelector with any standard Flux pattern that has multiple independent stores/slices, and are merged together withcombineReducers.
// store.jsimport { createStore, combineReducers } from 'redux';import personalDetailsReducer, { sliceKey as personalDetailsSliceKey } from './personalDetailsSlice';const reducer = combineReducers({ [personalDetailsSliceKey]: personalDetailsReducer});const store = createStore(reducer);// { personalDetails : { name: 'Ashish', age: '26', isEligibleToDrink: true } }export default store;
API Examples (createGlobalStateSelector)
createGlobalStateSelector can accept both object of local slice selector functions or single local slice selector function .
Pass an object of local slice selectors
const { selectX, selectY, selectZ } = createGlobalStateSelector( { selectX: (state: Record<string, any>): number => state.x, selectY: (state: Record<string, any>): number => state.y, selectZ: (state: Record<string, any>): string => state.z }, 'a', 'b');// Final store signature after combineReducersconst store = { a: { b: { x: 55, y: 65, z: 'temp' } } };selectX(store); // 55selectY(store); // 65selectZ(store); // 'temp'
Pass a local slice selector
const selectZ = createGlobalStateSelector((state: Record<string, any>): number => state.z, 'a', 'b');// Final store signature after combineReducersconst store = { a: { b: { x: 55, y: 65, z: 'temp' } } };selectZ(store); // 'temp'
FYI
createGlobalStateSelector usesObject.fromEntries andObject.entries which are not pollyfilled to reduce the package size. If needed, please add your own polyfills, or target your polyfills accordingly for Babel, Webpack, Rollup, etc.
License
MIT
About
Create global state selectors from local redux slice selectors.