useAsyncTask
Manages the manual execution, cancellation, and state of an asynchronous task with AbortSignal support.
Loading preview...
The useAsyncTask hook runs an asynchronous task on demand, tracks its pending state and result, and passes an AbortSignal to the task so in-flight work can be cancelled.
Installation
Usage
Examples
Passing Arguments
Arguments passed to run are forwarded to the task after the context object.
Cancellation
Call abort to cancel the in-flight task. The signal passed to the task is aborted, so fetch and other signal-aware APIs stop immediately.
API Reference
AsyncTaskContext
Context object passed as the first argument to the task.
Property
Specification
signalrequiredobject
Signal used to abort the in-flight task
Full Signature
UseAsyncTaskOptions
Configuration options for the task.
Property
Specification
initialData?TResult
Initial value for
data before the first run (and after reset)Full Signature
resetDataOnRun?uniondefault:false
Reset
data back to initialData when a new run startsFull Signature
onSuccess?function
Callback invoked when the task resolves successfully
Full Signature
Parameters
(dataTResultonError?function
Callback invoked when the task throws a non-abort error
Full Signature
Parameters
(errorErroronAbort?function
Callback invoked when the task is aborted
Full Signature
Parameters
(UseAsyncTaskReturn
Task state and controls returned by the hook.
Property
Specification
statusAsyncTaskStatus
Current execution status of the task
dataunion
Resolved data from the latest successful run
Full Signature
errorunion
Error from the latest failed run, or
nullFull Signature
isIdleunion
true when the task has not been run yet or was resetFull Signature
isPendingunion
true while the task is currently executingFull Signature
isSuccessunion
true when the latest run completed successfullyFull Signature
isErrorunion
true when the latest run failed with an errorFull Signature
isAbortedunion
true when the latest run was abortedFull Signature
runfunction
Executes the task with the given arguments (aborts any in-flight run)
Full Signature
Parameters
...argsTArgsabortfunction
Aborts the currently running task
Full Signature
Parameters
reason?unknownresetfunction
Aborts any in-flight run and resets state back to
idleFull Signature