mirror of
https://github.com/logto-io/logto.git
synced 2025-01-06 20:40:08 -05:00
38 lines
854 B
TypeScript
38 lines
854 B
TypeScript
|
import type { Nullable } from '@silverhand/essentials';
|
||
|
import { useCallback, useContext } from 'react';
|
||
|
|
||
|
import PageContext from '@/Providers/PageContextProvider/PageContext';
|
||
|
|
||
|
type Options = {
|
||
|
silent?: boolean;
|
||
|
};
|
||
|
|
||
|
const useApi = <Args extends unknown[], Response>(
|
||
|
api: (...args: Args) => Promise<Response>,
|
||
|
options?: Options
|
||
|
) => {
|
||
|
const { setLoading } = useContext(PageContext);
|
||
|
|
||
|
const request = useCallback(
|
||
|
async (...args: Args): Promise<[Nullable<unknown>, Response?]> => {
|
||
|
if (!options?.silent) {
|
||
|
setLoading(true);
|
||
|
}
|
||
|
|
||
|
try {
|
||
|
const result = await api(...args);
|
||
|
return [null, result];
|
||
|
} catch (error: unknown) {
|
||
|
return [error];
|
||
|
} finally {
|
||
|
setLoading(false);
|
||
|
}
|
||
|
},
|
||
|
[api, options?.silent, setLoading]
|
||
|
);
|
||
|
|
||
|
return request;
|
||
|
};
|
||
|
|
||
|
export default useApi;
|