Created
April 13, 2020 11:15
-
-
Save eczn/9e84bdbf67b79a2892fcb66e1b26bfa1 to your computer and use it in GitHub Desktop.
how to compose the existed Action / Reducer to make create multi instances on global redux store (combineReducer) in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // how to compose the existed Action / Reducer to make create multi instances on global redux store (combineReducer) | |
| // inspired from https://github.com/reduxjs/redux/issues/897 | |
| /** liftAction lifting your existed Action */ | |
| export function liftAction<LType extends string, Arg, A>( | |
| /** lift key */ | |
| liftedType: LType, | |
| /** original action generator */ | |
| actionGenerator: (...args: Arg[]) => A | |
| /* considering react-thunk so i use `HIGHT_ORDER_ACTION` refers to `LType` */ | |
| ): (...args: Arg[]) => { HIGHT_ORDER_ACTION: LType } & A { | |
| return function (...args) { | |
| const preAction = actionGenerator(...args) | |
| return { | |
| ...preAction, HIGHT_ORDER_ACTION: liftedType | |
| } | |
| } | |
| } | |
| /** liftReducer lifting your existed reducer */ | |
| export function liftReducer<LType extends string, A, State>( | |
| /** lift key */ | |
| liftedType: LType, | |
| /** origin reducer, tips: state may be undefined */ | |
| reducer: (state: State | undefined, action: A) => State | |
| ): (state: State | undefined, action: { HIGHT_ORDER_ACTION: LType } & A) => State { | |
| return function(state, action) { | |
| if (action.HIGHT_ORDER_ACTION === liftedType) { | |
| return reducer(state, action) | |
| } else { | |
| return state || reducer(state, action) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment