@taro-hooks/use-request
Version:
useRequest hook for Taro
50 lines (49 loc) • 1.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var core_1 = require("@taro-hooks/core");
var useRetryPlugin = function useRetryPlugin(fetchInstance, _ref) {
var retryInterval = _ref.retryInterval,
retryCount = _ref.retryCount;
var timerRef = (0, core_1.useRef)();
var countRef = (0, core_1.useRef)(0);
var triggerByRetry = (0, core_1.useRef)(false);
if (!retryCount) {
return {};
}
return {
onBefore: function onBefore() {
if (!triggerByRetry.current) {
countRef.current = 0;
}
triggerByRetry.current = false;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
},
onSuccess: function onSuccess() {
countRef.current = 0;
},
onError: function onError() {
countRef.current += 1;
if (retryCount === -1 || countRef.current <= retryCount) {
// Exponential backoff
var timeout = retryInterval != null ? retryInterval : Math.min(1000 * Math.pow(2, countRef.current), 30000);
timerRef.current = setTimeout(function () {
triggerByRetry.current = true;
fetchInstance.refresh();
}, timeout);
} else {
countRef.current = 0;
}
},
onCancel: function onCancel() {
countRef.current = 0;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
}
};
};
exports["default"] = useRetryPlugin;