useAsync

Utility

A React hook that manages asynchronous operations with built-in loading, error, and success states, making it easy to handle data fetching, form submissions, and other async tasks.

Installation

npm install @thibault.sh/hooks

API Reference

Signature


interface AsyncState<T> {
  isLoading: boolean;
  error: Error | null;
  value: T | null;
}

function useAsync<T>(asyncFunction: (...args: any[]) => Promise<T>): {
    execute: (...args: any[]) => Promise<void>;
    status: AsyncState<T>;
}

Parameters

NameTypeDescriptionDefault
asyncFunction
(...args: any[]) => Promise<T>
An asynchronous function that returns a Promise.-

Returns

AsyncHookReturn<T>

An object containing the execute function and current status of the async operation.

Properties:

PropertyTypeDescription
execute
(...args: any[]) => Promise<void>
A function that triggers the async operation. Accepts the same arguments as the input async function.
status
AsyncState<T>
Current state of the async operation containing loading state, error, and result value.
status.isLoading
boolean
Boolean indicating whether the async operation is currently in progress.
status.error
Error | null
Error object if the async operation failed, null otherwise.
status.value
T | null
The result of the async operation if successful, null otherwise.
useAsync Hook - React Asynchronous State Management