Notehooks

useAsync

Handle async operations with loading, error, and value states.

useAsync

The useAsync hook helps manage asynchronous operations such as API calls. It simplifies handling loading, error, and result states, making async logic more predictable and easier to manage within components.

Usage

import { useAsync } from "notehooks";

const fetchData = async (id: number) => {
  const response = await fetch(`https://api.example.com/items/${id}`);
  if (!response.ok) throw new Error("Failed to fetch");
  return response.json();
};

const MyComponent = () => {
  const { execute, value, loading, error } = useAsync(fetchData, {
    immediate: false,
  });

  return (
    <div>
      <button onClick={() => execute(123)} disabled={loading}>
        {loading ? "Loading..." : "Fetch Data"}
      </button>
      {error && <p className="text-red-500">{error.message}</p>}
      {value && <pre>{JSON.stringify(value, null, 2)}</pre>}
    </div>
  );
};

API

useAsync(fn, options?)

ArgumentTypeDescription
fn(...args: any[]) => Promise<T>The async function to execute.
optionsobjectConfiguration object.

Options

NameTypeDefaultDescription
immediatebooleanfalseIf true, executes the function immediately on mount.
initialArgsany[]undefinedArguments to pass if immediate is true.

Returns

NameTypeDescription
execute(...args) => Promise<T>Manually triggers the async function.
loadingbooleanTrue while the promise is pending.
errorError | nullThe error object, if any occurred.
valueT | nullThe resolved value from the async function.