vue-hooks-plus
Version:
Vue hooks library
45 lines (44 loc) • 1.14 kB
JavaScript
const vue = require("vue");
const useRetryPlugin = (fetchInstance, { retryInterval, retryCount }) => {
const timerRef = vue.ref();
const countRef = vue.ref(0);
const triggerByRetry = vue.ref(false);
if (!retryCount) {
return {};
}
return {
name: "retryPlugin",
onBefore: () => {
if (!triggerByRetry.value) {
countRef.value = 0;
}
triggerByRetry.value = false;
if (timerRef.value) {
clearTimeout(timerRef.value);
}
},
onSuccess: () => {
countRef.value = 0;
},
onError: () => {
countRef.value += 1;
if (retryCount === -1 || countRef.value <= retryCount) {
const timeout = retryInterval != null ? retryInterval : Math.min(1e3 * 2 ** countRef.value, 3e4);
timerRef.value = setTimeout(() => {
triggerByRetry.value = true;
fetchInstance.refresh();
}, timeout);
} else {
countRef.value = 0;
}
},
onCancel: () => {
countRef.value = 0;
if (timerRef.value) {
clearTimeout(timerRef.value);
}
}
};
};
module.exports = useRetryPlugin;
;