-
Notifications
You must be signed in to change notification settings - Fork 0
useAsync
useAsync is a hook that manages the lifecycle states of an async function (callback). This is helpful for complicated components as it handles loading and errors for you.
This is intended to handle expensive computation - if you're data fetching you're probably looking for Tanstack Query or SWR.
import { useAsync } from 'react-multitool';
function Demo() {
const someExpensiveComputation = async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
return 'Hello World';
}
const { data, error, loading, execute } = useAsync(someExpensiveComputation);
return (
<div>
{loading && <div>Loading...</div>}
{error && <div>Error: {error.message}</div>}
{data && <div>{data}</div>}
<button onClick={execute}>Execute</button>
</div>
)
}
If using Typescript, you can use the generic <T>
(defaults to any) to define the type of data - without this the return type will be inferred from the return value of the callback.
useAsync<T = any>(
callback: () => Promise<T>,
options?: UseAsyncOptions
): {
execute: () => void;
data: T | undefined;
pending: boolean;
error: Error | undefined;
}
Parameter | Type | Default | Description |
---|---|---|---|
immediate | boolean | false | If true, execute the callback immediately. |
allowConcurrent | boolean | true | If true, execute the callback even if the previous execution is still pending. |
If you've found something not quite right or something missing, please feel free to open an issue and I'll respond as soon as I can
If you'd like to contribute to React Multitool you're welcome to open a pull request - please note that for a feature to be accepted you'll need to provide tests and documentation! See contributing for more information.
I'm a full-time student, work part time and have several hobbies - React Multitool is provided for free, forever, as a resource that'll hopefully help someone with their next project! If you'd like to support what I do, I'd love for you to share this library around, visit my website or let me know of any interesting opportunities!