Skip to content

Instantly share code, notes, and snippets.

@willprice76
Last active May 1, 2020 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willprice76/7b4ee18a8ef91e21fdc9cdf7a3a97215 to your computer and use it in GitHub Desktop.
Save willprice76/7b4ee18a8ef91e21fdc9cdf7a3a97215 to your computer and use it in GitHub Desktop.
Generic React reducer for all component lifecycles
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