0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-02-03 21:48:55 -05:00
logto/packages/ui/src/hooks/use-api.ts

55 lines
1.3 KiB
TypeScript
Raw Normal View History

import { RequestErrorBody } from '@logto/schemas';
2021-08-30 11:30:54 +08:00
import { HTTPError } from 'ky';
import { useState, useCallback, useContext } from 'react';
import { PageContext } from '@/hooks/use-page-context';
type UseApi<T extends any[], U> = {
result?: U;
error: RequestErrorBody | undefined;
run: (...args: T) => Promise<void>;
};
function useApi<Args extends any[], Response>(
api: (...args: Args) => Promise<Response>
): UseApi<Args, Response> {
const [error, setError] = useState<RequestErrorBody>();
const [result, setResult] = useState<Response>();
const { setLoading } = useContext(PageContext);
const run = useCallback(
async (...args: Args) => {
setLoading(true);
// eslint-disable-next-line unicorn/no-useless-undefined
setError(undefined);
try {
const result = await api(...args);
setResult(result);
} catch (error: unknown) {
if (error instanceof HTTPError && error.response.body) {
const kyError = await error.response.json<RequestErrorBody>();
setError(kyError);
2022-01-27 19:26:34 +08:00
return;
}
// TODO: handle unknown server error
throw error;
} finally {
setLoading(false);
}
},
[api, setLoading]
);
return {
error,
result,
run,
};
}
export default useApi;