useAsyncPolling()
useAsyncPolling<
T,Args,E>(asyncFunction,delay,options?):UseAsyncResult<T,Args,E>
Defined in: hooks/async/useAsyncPolling.ts:45
A convenience hook that combines useAsync with usePolling.
It will:
- Use
useAsyncto manageloading,error, andresultstate. - Use
usePollingto callexecuteon a fixed interval.
Type Parameters
T
T
The type of the resolved value.
Args
Args extends unknown[] = []
Tuple of argument types passed to the async function.
E
E = Error
The error type (defaults to Error).
Parameters
asyncFunction
(...args) => Promise<T>
The async function to execute.
delay
Interval in milliseconds. Set to null to stop polling.
number | null
options?
Optional configuration.
immediate: Whether to run once immediately when mounted.
immediate?
boolean
Returns
UseAsyncResult<T, Args, E>
The same result object as useAsync.
Example
tsx
import { useAsyncPolling } from '@zl-asica/react';
const fetchStats = async () => {
const res = await fetch('/api/stats');
if (!res.ok) throw new Error('Failed to fetch stats');
return res.json();
};
const Stats = () => {
const { result, error, loading } = useAsyncPolling(fetchStats, 5000, {
immediate: true,
});
if (loading && !result) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
return <pre>{JSON.stringify(result, null, 2)}</pre>;
};