UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

43 lines (42 loc) 1.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useTimeoutWhen = void 0; var react_1 = require("react"); var noop_1 = require("../utils/noop"); /** * A setTimeout hook that calls a callback after a timeout duration * when a condition is true * * @param callback The callback to be invoked after timeout * @param timeoutDelayMs Amount of time in ms after which to invoke * @param when The condition which when true, sets the timeout * @see https://react-hooks.org/docs/useTimeoutWhen */ function useTimeoutWhen(callback, timeoutDelayMs, when) { if (timeoutDelayMs === void 0) { timeoutDelayMs = 0; } if (when === void 0) { when = true; } var savedRefCallback = (0, react_1.useRef)(); (0, react_1.useEffect)(function () { savedRefCallback.current = callback; }); function internalCallback() { var _a; (_a = savedRefCallback.current) === null || _a === void 0 ? void 0 : _a.call(savedRefCallback); } (0, react_1.useEffect)(function () { if (when) { // eslint-disable-next-line no-negated-condition if (typeof window !== "undefined") { var timeout_1 = window.setTimeout(internalCallback, timeoutDelayMs); return function () { window.clearTimeout(timeout_1); }; } else { console.warn("useTimeoutWhen: window is undefined."); } } return noop_1.noop; }, [timeoutDelayMs, when]); } exports.useTimeoutWhen = useTimeoutWhen;