beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
70 lines (69 loc) • 2.69 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var usePreviousValue_1 = __importDefault(require("./usePreviousValue"));
var defaultOptions = {
cancelOnUnmount: true,
cancelOnConditionChange: true,
};
/**
* An async-utility hook that accepts a callback function and a delay time (in milliseconds), then delays the
* execution of the given function by the defined time from when the condition verifies.
*/
var useConditionalTimeout = function (fn, milliseconds, condition, options) {
if (options === void 0) { options = defaultOptions; }
var opts = __assign(__assign({}, defaultOptions), (options || {}));
var timeout = (0, react_1.useRef)();
var callback = (0, react_1.useRef)(fn);
var _a = (0, react_1.useState)(false), isCleared = _a[0], setIsCleared = _a[1];
var prevCondition = (0, usePreviousValue_1.default)(condition);
// the clear method
var clear = (0, react_1.useCallback)(function () {
if (timeout.current) {
clearTimeout(timeout.current);
setIsCleared(true);
}
}, []);
// if the provided function changes, change its reference
(0, react_1.useEffect)(function () {
if (typeof fn === 'function') {
callback.current = fn;
}
}, [fn]);
// when the milliseconds change, reset the timeout
(0, react_1.useEffect)(function () {
if (condition && typeof milliseconds === 'number') {
timeout.current = setTimeout(function () {
callback.current();
}, milliseconds);
}
}, [condition, milliseconds]);
// when the condition change, clear the timeout
(0, react_1.useEffect)(function () {
if (prevCondition && condition !== prevCondition && opts.cancelOnConditionChange) {
clear();
}
}, [condition, options]);
// when component unmount clear the timeout
(0, react_1.useEffect)(function () { return function () {
if (opts.cancelOnUnmount) {
clear();
}
}; }, []);
return [isCleared, clear];
};
exports.default = useConditionalTimeout;