ahooks
Version:
react hooks library
70 lines (69 loc) • 2.76 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _throttle = _interopRequireDefault(require("lodash/throttle"));
var _react = require("react");
var _cancelledError = require("../utils/cancelledError");
var useThrottlePlugin = function useThrottlePlugin(fetchInstance, _ref) {
var throttleWait = _ref.throttleWait,
throttleLeading = _ref.throttleLeading,
throttleTrailing = _ref.throttleTrailing;
var throttledRef = (0, _react.useRef)(undefined);
var pendingRejectRef = (0, _react.useRef)(undefined);
var options = {};
if (throttleLeading !== undefined) {
options.leading = throttleLeading;
}
if (throttleTrailing !== undefined) {
options.trailing = throttleTrailing;
}
(0, _react.useEffect)(function () {
if (throttleWait) {
var _originRunAsync = fetchInstance.runAsync.bind(fetchInstance);
throttledRef.current = (0, _throttle["default"])(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];
}
(0, _cancelledError.cancelPendingPromise)(pendingRejectRef);
return new Promise(function (resolve, reject) {
var _a;
var callbackInvoked = false;
pendingRejectRef.current = reject;
(_a = throttledRef.current) === null || _a === void 0 ? void 0 : _a.call(throttledRef, function () {
callbackInvoked = true;
pendingRejectRef.current = undefined;
_originRunAsync.apply(void 0, args).then(resolve)["catch"](reject);
});
if (!callbackInvoked && options.trailing === false) {
(0, _cancelledError.cancelPendingPromise)(pendingRejectRef);
}
});
};
return function () {
var _a;
fetchInstance.runAsync = _originRunAsync;
(_a = throttledRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
(0, _cancelledError.cancelPendingPromise)(pendingRejectRef);
};
}
}, [throttleWait, throttleLeading, throttleTrailing]);
if (!throttleWait) {
return {};
}
return {
onCancel: function onCancel() {
var _a;
(_a = throttledRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
(0, _cancelledError.cancelPendingPromise)(pendingRejectRef);
}
};
};
var _default = exports["default"] = useThrottlePlugin;