Function useAsync

  • Type Parameters

    • T

      The type of the successful result

    • I = T

      The type of the initial value (defaults to T)

    • Args extends any[] = any[]

      The types of arguments the async function accepts

    Parameters

    • initial: I

      The initial value before the async operation completes

    • asyncFn: ((...args: Args) => Promise<T>)

      The async function to execute

        • (...args): Promise<T>
        • Parameters

          Returns Promise<T>

    • config: Partial<{
          init: boolean;
          rejectWhilePending: boolean;
      }> = {}
      • config.init If true, calls the async function immediately on mount
      • config.rejectWhilePending If true, prevents calling the function while status is pending

    Returns UseAsyncResult<T, I, Args>

    Object 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 otherwise
    • caller: Function to manually trigger the async operation
    • setResult: Function to manually update the result value

    Hook to handle asynchronous operations with status tracking and error handling

    const 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>;