useAsync
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.
Demo
1. Data Fetching
2. Form Submission
Installation
npm install @thibault.sh/hooks
Usage
import { useAsync } from "@thibault.sh/hooks";
function UserProfile() {
const { execute: fetchUser, status } = useAsync(async (userId: string) => {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error("Failed to fetch user");
return response.json();
});
return (
<div>
<button
onClick={() => fetchUser("123")}
disabled={status.isLoading}
>
{status.isLoading ? "Loading..." : "Load Profile"}
</button>
{status.error && <div>Error: {status.error.message}</div>}
{status.value && <div>Welcome, {status.value.name}!</div>}
</div>
);
}
API Reference
Returns
Object containing execute function, loading state, error, and value
Parameters
asyncFunction
An asynchronous function that returns a Promise. This function will be wrapped with loading and error handling logic.
(...args: any[]) => Promise<T>
Return Value
execute
A function that triggers the async operation. It accepts the same arguments as the input async function and handles the loading state and error catching automatically.
status
An object containing the current state of the async operation:
Boolean indicating whether the async operation is currently in progress.
Error object if the async operation failed, null otherwise.
The result of the async operation if successful, null otherwise.
Features
Loading State Management
Automatically tracks loading state during async operations, making it easy to show loading indicators and disable interactions.
Error Handling
Catches and stores errors from failed async operations, enabling proper error messaging and recovery flows.
Type Safety
Full TypeScript support with generics for proper typing of async function results and error handling.
Reusable Logic
Encapsulates common async operation patterns, reducing boilerplate and ensuring consistent error handling.