"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSafePromise = void 0;
var react_1 = require("react");
var ramda_1 = require("ramda");
var PromiseStub = new Promise(function () { });
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 = (0, react_1.useRef)(ramda_1.identity);
    var cancelPromise = function () { return cancelRef.current(); };
    (0, react_1.useEffect)(function () { return function () {
        if (cancelOnUnmount) {
            cancelPromise();
        }
    }; }, [] //eslint-disable-line
    );
    return (0, react_1.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
};
exports.useSafePromise = useSafePromise;
