Last active
May 1, 2020 14:03
-
-
Save willprice76/7b4ee18a8ef91e21fdc9cdf7a3a97215 to your computer and use it in GitHub Desktop.
Generic React reducer for all component lifecycles
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 type ActionState<T> = { | |
data?: T; | |
isBusy: boolean; | |
hasError: boolean; | |
errorMessage?: string; | |
}; | |
export type ActionResult<T> = | |
| { type: "busy" } | |
| { type: "success"; result: T } | |
| { type: "error"; error: string }; | |
export const createActionReducer = <T>() => ( | |
state: ActionState<T>, | |
action: ActionResult<T> | |
): ActionState<T> => { | |
switch (action.type) { | |
case "busy": | |
return { isBusy: true, hasError: false }; | |
case "success": | |
return { isBusy: false, hasError: false, data: action.result }; | |
case "error": | |
return { isBusy: false, hasError: true, errorMessage: action.error }; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment