@taro-hooks/use-request
Version:
useRequest hook for Taro
58 lines • 2.14 kB
JavaScript
import { debounce } from 'lodash-wechat';
import { useEffect, useMemo, useRef } from '@taro-hooks/core';
var useDebouncePlugin = function useDebouncePlugin(fetchInstance, _ref) {
var debounceWait = _ref.debounceWait,
debounceLeading = _ref.debounceLeading,
debounceTrailing = _ref.debounceTrailing,
debounceMaxWait = _ref.debounceMaxWait;
var debouncedRef = useRef();
var options = 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]);
useEffect(function () {
if (debounceWait) {
var _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
// @ts-ignore
debouncedRef.current = 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();
}
};
};
export default useDebouncePlugin;