HooksuseAsync

useAsync()

The useAsync() hook simplifies asynchronous logic management (like API calls) by providing reactive states for pending, success, and error outcomes.

Import

typescript
import { useAsync } from 'the-react-hooks';

Usage

Status:idle
Component.tsx
import { useAsync } from 'the-react-hooks';

const fetchData = (shouldFail) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      shouldFail 
        ? reject('Error!') 
        : resolve('Success!');
    }, 2000);
  });
};

export const Component = () => {
  const { execute, status, value, error } = useAsync(fetchData);

  return (
    <div>
      <button onClick={() => execute(false)}>
        Fetch Data
      </button>

      {status === 'pending' && <p>Loading...</p>}
      {status === 'success' && <p>Data: {value}</p>}
      {status === 'error' && <p>Error: {error}</p>}
    </div>
  );
}

API

Arguments

  • asyncFunction (...args: any[]) => Promise<T> The function to be executed. Must return a Promise.
  • immediate boolean (Optional) If true, the function will be executed immediately on mount. Defaults to false.

Returns

Returns an object with the following properties:
  • execute (...args) => Promise Function to manually trigger the async operation.
  • status 'idle' | 'pending' | 'success' | 'error' Current state of the operation.
  • value T | null The resolved data from the promise (if successful).
  • error E | null The error object (if rejected).
  • isPending boolean Helper boolean, true if status is 'pending'.