Skip to content

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>

PropertyTypeDefaultDescription
onSuccess(data: TData) => void-Called on successful execution
onError(error: Error) => void-Called on failed execution
onSettled() => void-Called after success or failure
initialDataTData | nullnullInitial data value

Return Type

UseAsyncActionReturn<TArgs, TData, TError>

PropertyTypeDescription
run(...args: TArgs) => Promise<TData | undefined>Execute the async action
isLoadingbooleanWhether action is in progress
errorTError | nullError from last failed execution
dataTData | nullData from last successful execution
hasRunbooleanWhether action has been executed at least once
reset() => voidReset 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')

See also