redux-scoped-reducer
Quickstart
Install the library
$ npm install redux-scoped-reducer --save
Basic Usage
// Import the library;// Create the reducer scoperconst createViewsReducer = ; // Some view reducer { // state here will be scoped to `user.views` if actiontype === 'INCREMENT_VIEWS' return ...state viewCount: stateviewCount + 1 ; return state;} // Scope the viewReducer functionconst scopedViewReducer = ; const state = user: views: viewCount: 0 // ... other pieces of state;const action = type: 'INCREMENT_VIEWS';const nextState = ;// {// user: {// views: {// viewCount: 1,// }// }// }
API
import createReducerScope from 'redux-scoped-reducer'; // scope can be dot separated to allow for deep path scoping.// Examples: 'user', 'user.views', 'user.views.viewCount', ...etctype createReducerScope = (scope: string) => ReducerCreator; type ReducerCreator = (Reducer) => Reducer; // Standard redux reducers and actions.// Type definitions included for completeness, but nothing special going on heretype Reducer = (state: any, action: Action) => any;type Action = { type: string, payload: any,};
More Usage Examples
;// The scoped reducer pattern works nicely with the `reduce-reducers` library; const createViewsReducer = ;const createCounterReducer = ; { if actiontype === 'INCREMENT_VIEWS' return ...state viewCount: stateviewCount + 1 ; return state;} { if actiontype === 'INCREMENT_COUNTER' return state + 1; return state;} const scopedViewReducer = ;const scopedCounterReducer = ;// scoped reducers can be easily composed using reduce reducersconst rootReducer = ; let lastState = user: views: viewCount: 0 meta: firstName: 'hello' lastName: 'world' counter: 0; const incrementCounterAction = type: 'INCREMENT_COUNTER';const incrementViewCountAction = type: 'INCREMENT_VIEWS'; let nextState = ; // Reference equality at root will be brokennextState !== lastState // Reference equality is maintained outside of the changed pathnextStateuser === lastStateuser lastState = nextState;nextState = ; // Reference equality at root will be brokennextState !== lastState // Reference equality is broken within the changed property pathnextStateuser !== lastStateusernextStateuserviews !== lastStateuserviews // Reference equality is maintained outside the changed property path,// even at properties adjacent to ones in the changed pathnextStateusermeta === lastStateusermeta