Skip to content

Instantly share code, notes, and snippets.

@nikosolihin
Forked from mattpocock/gist.ts
Created November 19, 2020 03:23
Show Gist options
  • Select an option

  • Save nikosolihin/5da5ee22a0b87a39734bad3211a07f9a to your computer and use it in GitHub Desktop.

Select an option

Save nikosolihin/5da5ee22a0b87a39734bad3211a07f9a to your computer and use it in GitHub Desktop.

Revisions

  1. @mattpocock mattpocock renamed this gist Oct 21, 2020. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @mattpocock mattpocock created this gist Oct 21, 2020.
    30 changes: 30 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    const endpointToPromiseMap = {
    [ApiEndpoint.FetchAllGoals]: fetchUserGoals,
    [ApiEndpoint.CurrentUser]: currentUser,
    };

    type PromiseValue<T extends Promise<any>> = T extends Promise<infer U>
    ? U
    : never;

    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    const useFetch = <E extends ApiEndpoint, L>(endpoint: E, args?: L) => {
    const prms = endpointToPromiseMap[endpoint];
    return _useFetch<PromiseValue<ReturnType<typeof endpointToPromiseMap[E]>>, L>(
    prms as any,
    args,
    );
    };

    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    const _useFetch = <T, L>(prms: (arg0?: L) => Promise<T>, args?: L) => {
    const isMounted = useRef(true);
    const [data, setData] = useState<T | null>(null);
    const [errorMessage, setErrorMessage] = useState<string>('');

    return {
    status,
    errorMessage,
    data,
    };
    };