UNPKG

@taro-hooks/use-request

Version:
63 lines (62 loc) 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var lodash_wechat_1 = require("lodash-wechat"); var core_1 = require("@taro-hooks/core"); var useDebouncePlugin = function useDebouncePlugin(fetchInstance, _ref) { var debounceWait = _ref.debounceWait, debounceLeading = _ref.debounceLeading, debounceTrailing = _ref.debounceTrailing, debounceMaxWait = _ref.debounceMaxWait; var debouncedRef = (0, core_1.useRef)(); var options = (0, core_1.useMemo)(function () { var ret = {}; if (debounceLeading !== undefined) { ret.leading = debounceLeading; } if (debounceTrailing !== undefined) { ret.trailing = debounceTrailing; } if (debounceMaxWait !== undefined) { ret.maxWait = debounceMaxWait; } return ret; }, [debounceLeading, debounceTrailing, debounceMaxWait]); (0, core_1.useEffect)(function () { if (debounceWait) { var _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); // @ts-ignore debouncedRef.current = (0, lodash_wechat_1.debounce)(function (callback) { callback(); }, debounceWait, options); // debounce runAsync should be promise // https://github.com/lodash/lodash/issues/4400#issuecomment-834800398 fetchInstance.runAsync = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve, reject) { debouncedRef.current == null ? void 0 : debouncedRef.current(function () { _originRunAsync.apply(void 0, args).then(resolve)["catch"](reject); }); }); }; return function () { var _debouncedRef$current; (_debouncedRef$current = debouncedRef.current) == null ? void 0 : _debouncedRef$current.cancel(); fetchInstance.runAsync = _originRunAsync; }; } }, [debounceWait, options]); if (!debounceWait) { return {}; } return { onCancel: function onCancel() { var _debouncedRef$current2; (_debouncedRef$current2 = debouncedRef.current) == null ? void 0 : _debouncedRef$current2.cancel(); } }; }; exports["default"] = useDebouncePlugin;