Appearance
useAsyncAction
Wraps an async function with loading, error, and data state management.
Signature
ts
function useAsyncAction<TArgs extends unknown[], TData = unknown, TError = Error>(
asyncFn: (...args: TArgs) => Promise<TData>,
options?: UseAsyncActionOptions<TData>
): UseAsyncActionReturn<TArgs, TData, TError>Parameters
asyncFn
The async function to wrap. Receives any arguments passed to run().
UseAsyncActionOptions<TData>
| Property | Type | Default | Description |
|---|---|---|---|
onSuccess | (data: TData) => void | - | Called on successful execution |
onError | (error: Error) => void | - | Called on failed execution |
onSettled | () => void | - | Called after success or failure |
initialData | TData | null | null | Initial data value |
Return Type
UseAsyncActionReturn<TArgs, TData, TError>
| Property | Type | Description |
|---|---|---|
run | (...args: TArgs) => Promise<TData | undefined> | Execute the async action |
isLoading | boolean | Whether action is in progress |
error | TError | null | Error from last failed execution |
data | TData | null | Data from last successful execution |
hasRun | boolean | Whether action has been executed at least once |
reset | () => void | Reset state to initial values |
retry | () => Promise<TData | undefined> | Retry with last arguments |
Types
AsyncActionState<TData, TError>
ts
interface AsyncActionState<TData = unknown, TError = Error> {
isLoading: boolean
error: TError | null
data: TData | null
hasRun: boolean
}Example
tsx
const { run, isLoading, error } = useAsyncAction(
async (id: string) => api.deleteItem(id),
{ onSuccess: () => toast.success('Deleted') }
)
await run('item-123')