Last active
May 9, 2020 13:42
-
-
Save phen0menon/975eb4757d0377bca15f3a8fafa080df to your computer and use it in GitHub Desktop.
Reducer helper for convenient reducer creation
This file contains 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
export interface Action { | |
type: string; | |
} | |
export type CreateReducerReducer<S, A> = (state: S, action: A) => S; | |
export type CreateReducerComponents<S, A> = Record< | |
string, | |
CreateReducerReducer<S, A> | |
>; | |
export const createReducer = <S, A extends Action>( | |
components: CreateReducerComponents<S, A>, | |
initialState: S | |
) => (state: S = initialState, action: A) => | |
components.hasOwnProperty(action.type) | |
? components[action.type](state, action) | |
: state; | |
/* | |
Usage: | |
export const someReducer = createReducer<State, Action>( | |
{ | |
[ActionTypes.SOME_ACTION]: (state, action) => { | |
// ... | |
} | |
}, | |
initialState | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment