react-use-async-action
v0.1.0
Published
A production-grade React hook for managing async actions with strong typing, lifecycle safety, and predictable state.
Downloads
8
Maintainers
Readme
react-use-async-action
A production-grade React hook for async actions with strong TypeScript inference, predictable state transitions, lifecycle-safe updates, and latest-call-wins behavior.
Features
- Typed
execute(...args)API inferred from your async function idle,loading,success, anderrorstatus trackingreset()support for returning to the initial state- Optional
onSuccess,onError, andonSettledcallbacks - Optional immediate execution with
initialArgs - Protection against stale in-flight requests overwriting newer results
- Safe state updates when components unmount
Installation
npm install react-use-async-actionUsage
import { useAsyncAction } from "react-use-async-action";
async function fetchUser(id: number) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error("Failed to fetch user");
}
return response.json() as Promise<{ id: number; name: string }>;
}
export function UserButton() {
const { execute, data, error, isLoading, reset, status } = useAsyncAction(
fetchUser,
{
onError: (caughtError) => {
console.error(caughtError);
}
}
);
return (
<div>
<button disabled={isLoading} onClick={() => void execute(1)}>
{isLoading ? "Loading..." : "Load user"}
</button>
<button onClick={reset}>Reset</button>
<p>Status: {status}</p>
{error ? <p>Something went wrong.</p> : null}
{data ? <p>{data.name}</p> : null}
</div>
);
}API
useAsyncAction(asyncFunction, options?)
Returns:
execute: Runs the async action and returns its resultdata: The latest successful resulterror: The latest thrown errorstatus: One ofidle,loading,success, orerrorisIdle,isLoading,isSuccess,hasError,hasLoadedreset: Resets the hook back to its initial state
Options:
initialData: Seed state before the first executionimmediate: Run automatically on mountinitialArgs: Arguments used whenimmediateis enabledonSuccess: Called after a successful executiononError: Called after a failed executiononSettled: Called after either success or failure
Development
npm install
npm run typecheck
npm test
npm run build