Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Reducer, Action, AnyAction } from 'redux';
  2.  
  3. export interface ActionMap<S, A extends Action = AnyAction> {
  4.   [key: string]: Reducer<S, A>;
  5. }
  6.  
  7. /**
  8.  * Creates a reducer which is a combination of all reducers passed in the action map. Each reducer in the action map
  9.  * handles the action whose type is equal to the key of the specific reducer in the map.
  10.  *
  11.  * @param {ActionMap<S>} actionMap The map of reducers.
  12.  * @param {S} initialState The initial state of the reducer tree.
  13.  *
  14.  * @returns {Reducer<S>} The combined reducer.
  15.  */
  16. export default function reducerWithActionMap<S, A extends Action = AnyAction>(
  17.   actionMap: ActionMap<S, A>,
  18.   initialState: S
  19. ): Reducer<S, A> {
  20.   const isDevelopment = process.env.REACT_APP_NODE_ENV !== 'production' && process.env.REACT_APP_NODE_ENV !== 'sandbox';
  21.   if (initialState == null && isDevelopment) {
  22.     throw new Error('Initial state cannot be null!');
  23.   }
  24.  
  25.   return (state = initialState, action) => {
  26.     const reducer = actionMap[action.type];
  27.     return reducer ? reducer(state, action) : state;
  28.   };
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement