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?)
| Argument | Type | Description |
|---|---|---|
fn | (...args: any[]) => Promise<T> | The async function to execute. |
options | object | Configuration object. |
Options
| Name | Type | Default | Description |
|---|---|---|---|
immediate | boolean | false | If true, executes the function immediately on mount. |
initialArgs | any[] | undefined | Arguments to pass if immediate is true. |
Returns
| Name | Type | Description |
|---|---|---|
execute | (...args) => Promise<T> | Manually triggers the async function. |
loading | boolean | True while the promise is pending. |
error | Error | null | The error object, if any occurred. |
value | T | null | The resolved value from the async function. |