UNPKG

refun

Version:

A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:

57 lines (46 loc) 1.82 kB
Object.defineProperty(exports, "__esModule", { value: true }); exports.mapDebouncedHandlerTimeout = exports.mapDebouncedHandlerFactory = void 0; var _react = require("react"); var _tsfn = require("tsfn"); const mapDebouncedHandlerFactory = (setFn, clearFn) => (handlerName, ...setFnArgs) => props => { const timerId = (0, _react.useRef)(null); const debouncedHandlerRef = (0, _react.useRef)(); const onUnmountRef = (0, _react.useRef)(); const currentPropsHandlerRef = (0, _react.useRef)(); const handlerArgsRef = (0, _react.useRef)(_tsfn.EMPTY_ARRAY); currentPropsHandlerRef.current = props[handlerName]; if (debouncedHandlerRef.current === _tsfn.UNDEFINED) { const timeoutCallback = () => { timerId.current = null; if ((0, _tsfn.isFunction)(currentPropsHandlerRef.current)) { currentPropsHandlerRef.current(...handlerArgsRef.current); } }; debouncedHandlerRef.current = (...args) => { if (timerId.current !== null) { clearFn(timerId.current); timerId.current = null; } handlerArgsRef.current = _tsfn.EMPTY_ARRAY; if ((0, _tsfn.isFunction)(currentPropsHandlerRef.current)) { handlerArgsRef.current = args; timerId.current = setFn(timeoutCallback, ...setFnArgs); } }; onUnmountRef.current = () => () => { if (timerId.current !== null) { clearFn(timerId.current); timerId.current = null; } }; } (0, _react.useEffect)(onUnmountRef.current, _tsfn.EMPTY_ARRAY); return { ...props, [handlerName]: debouncedHandlerRef.current }; }; exports.mapDebouncedHandlerFactory = mapDebouncedHandlerFactory; const mapDebouncedHandlerTimeout = mapDebouncedHandlerFactory(setTimeout, clearTimeout); exports.mapDebouncedHandlerTimeout = mapDebouncedHandlerTimeout;