@taro-hooks/use-request
Version:
useRequest hook for Taro
56 lines (55 loc) • 2.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var lodash_wechat_1 = require("lodash-wechat");
var core_1 = require("@taro-hooks/core");
var useThrottlePlugin = function useThrottlePlugin(fetchInstance, _ref) {
var throttleWait = _ref.throttleWait,
throttleLeading = _ref.throttleLeading,
throttleTrailing = _ref.throttleTrailing;
var throttledRef = (0, core_1.useRef)();
var options = {};
if (throttleLeading !== undefined) {
options.leading = throttleLeading;
}
if (throttleTrailing !== undefined) {
options.trailing = throttleTrailing;
}
(0, core_1.useEffect)(function () {
if (throttleWait) {
var _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
// @ts-ignore
throttledRef.current = (0, lodash_wechat_1.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();
}
};
};
exports["default"] = useThrottlePlugin;