Last active
February 7, 2024 06:39
-
-
Save nothingrealhappen/0b4ddf1740ed0ec961c5e357f27e2610 to your computer and use it in GitHub Desktop.
useLoadingIndicator
This file contains hidden or 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
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