import { useCallback, useRef, useState } from 'react';
import { queryStatus } from '@wix/bex-core';
import once from 'lodash/once';
export function usePromiseState(_promiseFn, { errorMonitor, onError, }) {
    const [status, setStatus] = useState(() => ({
        ...queryStatus.idle,
        error: null,
        isFetching: false,
    }));
    const promiseFnRef = useRef(_promiseFn);
    const fetchOnce = useCallback(once(async () => {
        let newStatus;
        try {
            setStatus({
                ...queryStatus.loading,
                error: null,
                isFetching: true,
            });
            const data = await promiseFnRef.current();
            newStatus = {
                ...queryStatus.success,
                error: null,
                isFetching: false,
                data,
            };
            setStatus(newStatus);
        }
        catch (err) {
            onError?.({
                err,
                isOnline: true,
            });
            errorMonitor.captureException(err);
            newStatus = {
                ...queryStatus.error,
                error: err,
                isFetching: false,
            };
            setStatus(newStatus);
        }
        return newStatus;
    }), []);
    return {
        fetchOnce,
        status,
        promiseFnRef,
    };
}
//# sourceMappingURL=usePromiseState.js.map