import { useRef, useCallback, useEffect } from 'react';
import { identity } from 'ramda';
var PromiseStub = new Promise(function () { });
export var useSafePromise = function (_a) {
    var _b = _a === void 0 ? {} : _a, _c = _b.cancelPrevious, cancelPrevious = _c === void 0 ? true : _c, _d = _b.cancelOnUnmount, cancelOnUnmount = _d === void 0 ? true : _d;
    var cancelRef = useRef(identity);
    var cancelPromise = function () { return cancelRef.current(); };
    useEffect(function () { return function () {
        if (cancelOnUnmount) {
            cancelPromise();
        }
    }; }, [] //eslint-disable-line
    );
    return useCallback(function (promise) {
        if (cancelPrevious) {
            cancelPromise();
        }
        return new Promise(function (resolve, reject) {
            cancelRef.current = function () { return reject('canceled'); };
            promise.then(resolve, reject);
        }).catch(function (error) {
            if (error === 'canceled') {
                return PromiseStub;
            }
            else {
                throw error;
            }
        });
    }, []); //eslint-disable-line
};
