UNPKG

refun

Version:

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

62 lines (53 loc) 2.37 kB
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import { useRef, useEffect } from 'react'; import { isFunction, UNDEFINED, EMPTY_ARRAY } from 'tsfn'; export var mapDebouncedHandlerFactory = function mapDebouncedHandlerFactory(setFn, clearFn) { return function (handlerName) { for (var _len = arguments.length, setFnArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { setFnArgs[_key - 1] = arguments[_key]; } return function (props) { var timerId = useRef(null); var debouncedHandlerRef = useRef(); var onUnmountRef = useRef(); var currentPropsHandlerRef = useRef(); var handlerArgsRef = useRef(EMPTY_ARRAY); currentPropsHandlerRef.current = props[handlerName]; if (debouncedHandlerRef.current === UNDEFINED) { var timeoutCallback = function timeoutCallback() { timerId.current = null; if (isFunction(currentPropsHandlerRef.current)) { currentPropsHandlerRef.current.apply(currentPropsHandlerRef, _toConsumableArray(handlerArgsRef.current)); } }; debouncedHandlerRef.current = function () { if (timerId.current !== null) { clearFn(timerId.current); timerId.current = null; } handlerArgsRef.current = EMPTY_ARRAY; if (isFunction(currentPropsHandlerRef.current)) { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } handlerArgsRef.current = args; timerId.current = setFn.apply(void 0, [timeoutCallback].concat(setFnArgs)); } }; onUnmountRef.current = function () { return function () { if (timerId.current !== null) { clearFn(timerId.current); timerId.current = null; } }; }; } useEffect(onUnmountRef.current, EMPTY_ARRAY); return Object.assign({}, props, _defineProperty({}, handlerName, debouncedHandlerRef.current)); }; }; }; export var mapDebouncedHandlerTimeout = mapDebouncedHandlerFactory(setTimeout, clearTimeout); //# sourceMappingURL=map-debounced-handler.js.map