@supunlakmal/hooks
Version:
A collection of reusable React hooks
32 lines (31 loc) • 1.27 kB
TypeScript
/**
* Represents the state of an asynchronous operation.
*
* @template T The type of the value returned by the async function.
* @template E The type of the error thrown by the async function (defaults to Error).
*/
interface AsyncState<T, E = Error> {
loading: boolean;
error: E | null;
value: T | null;
}
/**
* Represents the return value of the useAsync hook.
*
* @template T The type of the value returned by the async function.
* @template E The type of the error thrown by the async function.
*/
interface UseAsyncReturn<T, E = Error> extends AsyncState<T, E> {
execute: () => Promise<void>;
}
/**
* Custom hook to manage the state of an asynchronous function call.
*
* @template T The expected type of the successful result.
* @template E The expected type of the error (defaults to Error).
* @param {() => Promise<T>} asyncFunction The asynchronous function to execute.
* @param {boolean} [immediate=true] Whether to execute the function immediately on mount. Defaults to true.
* @returns {UseAsyncReturn<T, E>} An object containing the loading state, error, value, and an execute function.
*/
export declare const useAsync: <T, E = Error>(asyncFunction: () => Promise<T>, immediate?: boolean) => UseAsyncReturn<T, E>;
export {};