@taro-hooks/use-request
Version:
useRequest hook for Taro
51 lines • 1.91 kB
JavaScript
import { throttle } from 'lodash-wechat';
import { useEffect, useRef } from '@taro-hooks/core';
var useThrottlePlugin = function useThrottlePlugin(fetchInstance, _ref) {
var throttleWait = _ref.throttleWait,
throttleLeading = _ref.throttleLeading,
throttleTrailing = _ref.throttleTrailing;
var throttledRef = useRef();
var options = {};
if (throttleLeading !== undefined) {
options.leading = throttleLeading;
}
if (throttleTrailing !== undefined) {
options.trailing = throttleTrailing;
}
useEffect(function () {
if (throttleWait) {
var _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
// @ts-ignore
throttledRef.current = throttle(function (callback) {
callback();
}, throttleWait, options);
// throttle 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) {
throttledRef.current == null ? void 0 : throttledRef.current(function () {
_originRunAsync.apply(void 0, args).then(resolve)["catch"](reject);
});
});
};
return function () {
var _throttledRef$current;
fetchInstance.runAsync = _originRunAsync;
(_throttledRef$current = throttledRef.current) == null ? void 0 : _throttledRef$current.cancel();
};
}
}, [throttleWait, throttleLeading, throttleTrailing]);
if (!throttleWait) {
return {};
}
return {
onCancel: function onCancel() {
var _throttledRef$current2;
(_throttledRef$current2 = throttledRef.current) == null ? void 0 : _throttledRef$current2.cancel();
}
};
};
export default useThrottlePlugin;