Skip to content

useAsync

React hook to handle async operations.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useAsync
sh
npx @novajslabs/cli add useAsync
sh
pnpm dlx @novajslabs/cli add useAsync

Or copy and paste the code into your project:

ts
import {useState, useCallback} from 'react';

interface UseAsyncState<T> {
    data: T | null;
    isLoading: boolean;
    error: Error | null;
    isSuccess: boolean;
}

export const useAsync = <T>() => {
    const [state, setState] = useState<UseAsyncState<T>>({
        data: null,
        isLoading: false,
        error: null,
        isSuccess: false
    });

    const execute = useCallback(async (asyncFunction: () => Promise<T>) => {
        setState((prev) => ({...prev, isLoading: true, error: null}));

        try {
            const result = await asyncFunction();
            setState({
                data: result,
                isLoading: false,
                error: null,
                isSuccess: true
            });
            return result;
        } catch (error) {
            setState({
                data: null,
                isLoading: false,
                error: error as Error,
                isSuccess: false
            });
            throw error;
        }
    }, []);

    return {execute, ...state};
};
js
import {useState, useCallback} from 'react';

export const useAsync = () => {
    const [state, setState] = useState({
        data: null,
        isLoading: false,
        error: null,
        isSuccess: false
    });

    const execute = useCallback(async (asyncFunction) => {
        setState((prev) => ({...prev, isLoading: true, error: null}));

        try {
            const result = await asyncFunction();
            setState({
                data: result,
                isLoading: false,
                error: null,
                isSuccess: true
            });
            return result;
        } catch (error) {
            setState({
                data: null,
                isLoading: false,
                error: error,
                isSuccess: false
            });
            throw error;
        }
    }, []);

    return {execute, ...state};
};

Requirements

React 16.8 or higher

Return values

execute

Type: (asyncFunction: () => Promise<T>) => Promise<T>

Executes the asynchronous operation provided as an argument.

data

Type: T | null

Holds the result of the asynchronous operation if it resolves successfully. It is null while the operation is in progress or if an error occurs.

isLoading

Type: boolean

Indicates whether the asynchronous operation is in progress. It is true while the asynchronous function is being executed.

error

Type: Error | null

Contains the error caught if the asynchronous operation fails. It is null when there are no errors.

isSuccess

Type: boolean

Indicates whether the asynchronous operation completed successfully. It is true only if no errors occurred.

Examples of common use cases