From fef36bc49baed5ff4f134c2ca6d94153516f9bcc Mon Sep 17 00:00:00 2001 From: Angelo Ashmore <angeloashmore@users.noreply.github.com> Date: Fri, 8 Oct 2021 15:18:43 -1000 Subject: [PATCH] fix: use string union over enum for hook states --- src/index.ts | 7 +++++-- src/types.ts | 22 +--------------------- src/useStatefulPrismicClientMethod.ts | 12 +++++++----- 3 files changed, 13 insertions(+), 28 deletions(-) diff --git a/src/index.ts b/src/index.ts index 701cc3e..48a083a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,5 +47,8 @@ export { useSinglePrismicDocument, } from "./hooks"; -export { PrismicClientHookState } from "./types"; -export type { JSXMapSerializer, JSXFunctionSerializer } from "./types"; +export type { + JSXMapSerializer, + JSXFunctionSerializer, + PrismicClientHookState, +} from "./types"; diff --git a/src/types.ts b/src/types.ts index de01a9d..4f44b59 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,24 +20,4 @@ export type JSXMapSerializer = prismicR.RichTextMapSerializer<JSX.Element>; /** * States of a `@prismicio/client` hook. */ -export const enum PrismicClientHookState { - /** - * The hook has not started fetching. - */ - IDLE, - - /** - * The hook is fetching data. - */ - PENDING, - - /** - * The hook sucessfully fetched data. - */ - SUCCEEDED, - - /** - * The hook failed to fetch data. - */ - FAILED, -} +export type PrismicClientHookState = "idle" | "loading" | "loaded" | "failed"; diff --git a/src/useStatefulPrismicClientMethod.ts b/src/useStatefulPrismicClientMethod.ts index d2851c7..285bd86 100644 --- a/src/useStatefulPrismicClientMethod.ts +++ b/src/useStatefulPrismicClientMethod.ts @@ -26,24 +26,26 @@ const reducer = <TData>( ): StateMachineState<TData> => { switch (action[0]) { case "start": { - return { state: PrismicClientHookState.PENDING }; + return { state: "loading" }; } case "succeed": { - return { state: PrismicClientHookState.SUCCEEDED, data: action[1] }; + return { state: "loaded", data: action[1] }; } case "fail": { return { ...state, - state: PrismicClientHookState.FAILED, + state: "failed", error: action[1], }; } } }; -const initialState = { state: PrismicClientHookState.IDLE } as const; +const initialState: StateMachineState<never> = { + state: "idle", +}; type UnwrapPromise<T> = T extends Promise<infer U> ? U : T; @@ -148,7 +150,7 @@ export const useStatefulPrismicClientMethod = < React.useEffect( () => { - if (state.state === PrismicClientHookState.IDLE && !skip) { + if (state.state === "idle" && !skip) { dispatch(["start"]); method .call(client, ...argsWithoutParams, params)