45 lines
1.7 KiB
TypeScript
45 lines
1.7 KiB
TypeScript
// src/hooks/useApiOnMount.ts
|
|
import { useEffect } from 'react';
|
|
import { useApi } from './useApi'; // Correctly import from the same directory
|
|
|
|
interface UseApiOnMountOptions {
|
|
enabled?: boolean;
|
|
}
|
|
|
|
/**
|
|
* A custom React hook that automatically executes an API call when the component mounts
|
|
* or when specified dependencies change. It wraps the `useApi` hook.
|
|
*
|
|
* @template T The expected data type from the API's JSON response.
|
|
* @param apiFunction The API client function to execute.
|
|
* @param deps An array of dependencies that will trigger a re-fetch when they change.
|
|
* @param args The arguments to pass to the API function.
|
|
* @returns An object containing:
|
|
* - `loading`: A boolean indicating if the request is in progress.
|
|
* - `isRefetching`: A boolean indicating if a non-initial request is in progress.
|
|
* - `error`: An `Error` object if the request fails, otherwise `null`.
|
|
* - `data`: The data returned from the API, or `null` initially.
|
|
*/
|
|
export function useApiOnMount<T, TArgs extends unknown[]>(
|
|
apiFunction: (...args: [...TArgs, AbortSignal?]) => Promise<Response>,
|
|
deps: React.DependencyList = [],
|
|
options: UseApiOnMountOptions = {},
|
|
...args: TArgs
|
|
) {
|
|
const { enabled = true } = options;
|
|
// Pass the generic types through to the underlying useApi hook for full type safety.
|
|
const { execute, ...rest } = useApi<T, TArgs>(apiFunction);
|
|
|
|
useEffect(() => {
|
|
if (!enabled) {
|
|
return;
|
|
}
|
|
// The `execute` function is memoized by `useCallback` in the `useApi` hook.
|
|
// The `args` are spread into the dependency array to ensure the effect re-runs
|
|
// if the arguments to the API call change.
|
|
execute(...args);
|
|
}, [execute, enabled, ...deps, ...args]);
|
|
|
|
return rest;
|
|
}
|