Function: useAsync()
useAsync<
T,A,E>(asyncFn,options?):UseAsyncReturn<T,A,E>
Defined in: use-async.ts:112
Runs an async function and tracks its status, data and error.
Nothing runs until you call run, unless you set immediate. Only the
latest run updates the state, so a slow earlier call can never overwrite a
newer result. run never rejects; it resolves with an AsyncResult,
so event handlers need no try/catch. The latest asyncFn, onSuccess
and onError are always used, so inline functions are safe, and run and
reset keep the same identity across renders. State is never updated after
unmount.
It does not abort the underlying work. To cancel a request when a new one
starts, use useSequentialRequest; to fetch JSON from a URL, use useApi.
Under React StrictMode in development, immediate runs the function twice.
Type Parameters
T
T
The type of data the async function resolves with.
A
A extends unknown[] = []
The argument list of the async function.
E
E = unknown
The type of error the async function rejects with. Default is unknown.
Parameters
asyncFn
(...args) => Promise<T>
The function to run. It receives the arguments passed to run.
options?
UseAsyncOptions<T, A, E> = {}
Optional behavior flags and callbacks.
Returns
UseAsyncReturn<T, A, E>
The state and controls of the async function.
Examples
const { run, data, error, isPending } = useAsync(
(id: string) => fetchUser(id)
);
<button onClick={() => run("42")} disabled={isPending}>Load</button>
// Run on mount, and react to the outcome
const { data, status, run } = useAsync(loadSettings, {
immediate: true,
onError: (error) => reportError(error),
});
For a live, editable example, see the useAsync docs page.