Created
March 8, 2018 12:19
-
-
Save Reshetnyak/0ab64cf6339adc54d691ec2398677f99 to your computer and use it in GitHub Desktop.
Redux Action creators. Class + enum approach
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
/* | |
* 'type' function is taken from here https://github.com/Reshetnyak/toolbox/blob/master/type/type.ts | |
*/ | |
/* [start] current approach */ | |
// action without payload | |
export const OPEN_MODAL_TYPE = type('OPEN_MODAL'); | |
export interface OpenModalAction { | |
type: typeof OPEN_MODAL_TYPE; | |
} | |
export function openModalAction(): OpenModalAction { | |
return { | |
type: OPEN_MODAL_TYPE | |
}; | |
} | |
// action with payload | |
export const INCREMENT_ACTION_TYPE = type('INCREMENT_ACTION'); | |
export interface IncrementAction { | |
type: typeof INCREMENT_ACTION_TYPE; | |
payload: number; | |
} | |
export function incrementAction(params: number): IncrementAction { | |
return { | |
type: INCREMENT_ACTION_TYPE, | |
payload: number | |
}; | |
} | |
// and in reducers: | |
// ... | |
export function someReducer(state: number = 0, action: someAction): someState { | |
switch (action.type) { | |
case INCREMENT_ACTION_TYPE: { | |
return state + action.payload; | |
} | |
} | |
/* [end] current approach */ | |
/* [start] suggestion to reduce boilerplate */ | |
// actions.ts | |
export enum ActionTypes { | |
Increment = 'INCREMENT', | |
OpenModal = 'OPEN_MODAL' | |
} | |
export class OpenModalAction { | |
public readonly type = type(ActionTypes.OpenModal); | |
} | |
export class Increment { | |
public readonly type = type(ActionTypes.Increment); | |
constructor(public readonly payload: number) {} | |
} | |
// reducer.ts | |
switch (action.type) { | |
case ActionTypes.OpenModal: {/*...*/ } | |
case ActionTypes.Increment: { | |
return state + action.payload; | |
} | |
/* [end] suggestion to reduce boilerplate */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment