1 import { useCallback, useEffect, useState } from 'react';
3 import useApi from './useApi';
4 import useAsync from './useAsync';
6 export type QueryFunction = (...args: any[]) => { method: string; url: string };
8 interface Result<R, U extends any[]> {
12 request: (...args: U) => Promise<R>;
15 const useApiResult = <R, F extends QueryFunction = QueryFunction>(
20 ): Result<R, Parameters<F>> => {
21 const request = useApi();
22 const { loading, result, error, run } = useAsync(true);
23 const [calledManually, setCalledManually] = useState(!lazy);
25 // Either user specified dependencies or empty array to always cancel requests on unmount.
26 const hookDependencies = dependencies || [];
29 const requestAndSetResults = useCallback(
30 (...args: Parameters<F>) => {
31 const promise = request<R>(fn(...args));
33 setCalledManually(true);
40 if (!calledManually) {
44 // If user has specified any dependencies, auto request
46 requestAndSetResults(...([] as unknown as Parameters<F>)).catch(() => {
47 // catch the error to stop the "uncaught exception error"
50 }, [...hookDependencies]);
52 if (error && throwOnError) {
53 // Throw in render to allow the error boundary to catch it
61 request: requestAndSetResults,
65 export default useApiResult;