'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports['default'] = useCacheErrors;

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _useForceUpdate = require('../utils/useForceUpdate');

var _useForceUpdate2 = _interopRequireDefault(_useForceUpdate);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

/**
 * Always debounce error to avoid [error -> null -> error] blink
 */
function useCacheErrors(errors, changeTrigger, directly) {
    var cacheRef = React.useRef({
        errors: errors,
        visible: !!errors.length
    });
    var forceUpdate = (0, _useForceUpdate2['default'])();
    var update = function update() {
        var prevVisible = cacheRef.current.visible;
        var newVisible = !!errors.length;
        var prevErrors = cacheRef.current.errors;
        cacheRef.current.errors = errors;
        cacheRef.current.visible = newVisible;
        if (prevVisible !== newVisible) {
            changeTrigger(newVisible);
        } else if (prevErrors.length !== errors.length || prevErrors.some(function (prevErr, index) {
            return prevErr !== errors[index];
        })) {
            // @ts-ignore
            forceUpdate();
        }
    };
    React.useEffect(function () {
        if (!directly) {
            var timeout = setTimeout(update, 10);
            return function () {
                return clearTimeout(timeout);
            };
        }
    }, [errors]);
    if (directly) {
        update();
    }
    return [cacheRef.current.visible, cacheRef.current.errors];
}
module.exports = exports['default'];