Some checks failed
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Failing after 37m20s
30 lines
1.1 KiB
TypeScript
30 lines
1.1 KiB
TypeScript
// src/hooks/useApiOnMount.ts
|
|
import { useEffect } from 'react';
|
|
import { useApi } from './useApi'; // Correctly import from the same directory
|
|
|
|
/**
|
|
* 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.
|
|
* - `error`: An `Error` object if the request fails, otherwise `null`.
|
|
* - `data`: The data returned from the API, or `null` initially.
|
|
*/
|
|
export function useApiOnMount<T>(
|
|
apiFunction: (...args: any[]) => Promise<Response>,
|
|
deps: React.DependencyList = [],
|
|
...args: Parameters<typeof apiFunction>
|
|
) {
|
|
const { execute, ...rest } = useApi<T>(apiFunction);
|
|
|
|
useEffect(() => {
|
|
execute(...args);
|
|
}, deps);
|
|
|
|
return rest;
|
|
} |