The type of the initial value (defaults to T)
The types of arguments the async function accepts
The initial value before the async operation completes
The async function to execute
config.init If true, calls the async function immediately on mountconfig.rejectWhilePending If true, prevents calling the function while status is pendingObject containing:
status: Current state of the async operation ('IDLE'|'PENDING'|'FULFILLED'|'REJECTED')result: The current value (initial value or successful result)error: Error object if status is 'REJECTED', undefined otherwisecaller: Function to manually trigger the async operationsetResult: Function to manually update the result valueconst async1 = useAsync(undefined, () => new Promise((resolve) => {
setTimeout(() => {
resolve('Hello World');
}, 2500);
}) as Promise<string>, { init: true });
const async2 = useAsync(undefined, () => new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Hello World'));
}, 5000);
}));
useEffect(() => {
if (async1.status === 'FULFILLED') {
async2.caller();
}
}, [async1.status]);
if (async2.status === 'PENDING') return <h1>Loading 2 ...</h1>;
if (async2.status === 'REJECTED') return <h1>Error: {async2.error?.message}</h1>;
if (async1.status === 'PENDING') return <h1>Loading 1 ...</h1>;
if (async1.status === 'FULFILLED') return <h1>Result: {async1.result}</h1>;
else return <h1>Won't Get Here</h1>;
The type of the successful result