Skip to content

useAsync()

useAsync<T, E>(asyncFunction, immediate?): object

Defined in: src/hooks/async/useAsync.ts:42

A custom React hook to handle asynchronous functions with state management for loading, error, and result. Useful for API calls or other asynchronous operations.

Type Parameters

T

The type of the result returned by the asynchronous function.

E = Error

The type of the error (defaults to Error).

Parameters

asyncFunction

() => Promise<T>

The asynchronous function to execute.

immediate?

boolean = true

Whether to execute the function immediately upon hook initialization.

Returns

object

An object containing:

  • execute: A function to trigger the async operation manually.
  • loading: A boolean indicating whether the async operation is in progress.
  • error: An error object if the operation fails.
  • result: The result of the successful async operation.

execute()

execute: () => Promise<void>

Returns

Promise<void>

loading

loading: boolean

error

error: null | E

result

result: null | T

Example

tsx
import { useAsync } from '@zl-asica/react';

const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) throw new Error('Failed to fetch data');
  return response.json();
};

const MyComponent = () => {
  const { execute, loading, error, result } = useAsync(fetchData, true);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return <div>Result: {JSON.stringify(result)}</div>;
};

Released under the MIT License.