import { useMemo, useRef } from 'react';
import { useAsync, } from '../useAsync/index.js';
export function useAsyncAbortable(asyncFn, initialValue) {
    const abortController = useRef();
    const fn = async (...args) => {
        abortController.current?.abort();
        const ac = new AbortController();
        abortController.current = ac;
        return asyncFn(ac.signal, ...args).finally(() => {
            if (abortController.current === ac) {
                abortController.current = undefined;
            }
        });
    };
    const [state, asyncActions, asyncMeta] = useAsync(fn, initialValue);
    return [
        state,
        useMemo(() => {
            const actions = {
                reset() {
                    actions.abort();
                    asyncActions.reset();
                },
                abort() {
                    abortController.current?.abort();
                },
            };
            return {
                ...asyncActions,
                ...actions,
            };
        }, []),
        { ...asyncMeta, abortController: abortController.current },
    ];
}
