import { useCallback, useMemo, useState } from "react";
export function useRawAsynControl(functionsToWrap, [error, setError], [loading, setLoading]) {
    const _process = useCallback(async (asyncFn) => {
        try {
            setLoading(true);
            setError(undefined);
            if (asyncFn instanceof Promise)
                await asyncFn;
            else
                return await asyncFn();
        }
        catch (e) {
            if (process.env.NODE_ENV === "development")
                console.error(e);
            setError(e);
            throw e;
        }
        finally {
            setLoading(false);
        }
    }, []);
    const { functionsToMemoize, other } = Object.entries(functionsToWrap || {}).reduce((r, [k, func]) => {
        return {
            ...r,
            ...(typeof func === "function"
                ? {
                    functionsToMemoize: {
                        ...r.functionsToMemoize,
                        [k]: func,
                    },
                }
                : {
                    other: {
                        ...r.other,
                        [k]: func,
                    },
                }),
        };
    }, {
        functionsToMemoize: {},
        other: {},
    });
    return {
        process: _process,
        loading,
        error,
        setError,
        setLoading,
        ...other,
        ...Object.entries(functionsToMemoize).reduce((r, [k, v]) => ({
            ...r,
            [k]: useMemo(() => (...args) => _process(() => v(...args)), [v]),
        }), {}),
    };
}
export function useAsyncControl(functionsToWrap) {
    const error = useState();
    const loading = useState(false);
    return useRawAsynControl(functionsToWrap, error, loading);
}
/**
 * This hook provides a way to handle async operations storing the loading state, or the error when it fails, it does not store information returned from the functions.
 * @param functionsToWrap The functions to wrap in control.
 * @returns
 */
export default useAsyncControl;
//# sourceMappingURL=useAsyncControl.js.map