Skip to content

Instantly share code, notes, and snippets.

@liyaodong
Last active February 7, 2024 06:39
Show Gist options
  • Save liyaodong/0b4ddf1740ed0ec961c5e357f27e2610 to your computer and use it in GitHub Desktop.
Save liyaodong/0b4ddf1740ed0ec961c5e357f27e2610 to your computer and use it in GitHub Desktop.
useLoadingIndicator
import { useState } from "react";
type FunctionArgs<T> = T extends (...args: infer Args) => unknown
? Args
: never;
type FunctionReturn<T> = T extends (...args: unknown[]) => infer Return
? Return
: never;
export const useLoadingIndicator = <
TCallback extends (...args: never[]) => never | void
>(
originFetcher: TCallback
) => {
const [loading, setLoading] = useState(false);
const fetcher = async (
...args: FunctionArgs<TCallback>
): Promise<FunctionReturn<TCallback>> => {
setLoading(true);
try {
const result = (await originFetcher(
...args
)) as unknown as FunctionReturn<TCallback>;
setLoading(false);
return result;
} catch (e) {
setLoading(false);
throw e;
}
};
return {
fetcher,
loading,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment