vue-hooks-plus
Version:
Vue hooks library
57 lines (56 loc) • 1.51 kB
JavaScript
import { ref, watchEffect, unref } from "vue";
import isDocumentVisible from "../utils/isDocumentVisible";
import subscribeReVisible from "../utils/subscribeReVisible";
const usePollingPlugin = (fetchInstance, { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 }) => {
let timeouter;
const unsubscribeRef = ref();
const countRef = ref(0);
const stopPolling = () => {
var _a;
if (timeouter) {
clearTimeout(timeouter);
}
(_a = unsubscribeRef.value) == null ? void 0 : _a.call(unsubscribeRef);
};
watchEffect(() => {
if (!unref(pollingInterval)) {
stopPolling();
}
});
if (!unref(pollingInterval)) {
return {};
}
return {
name: "pollingPlugin",
onBefore: () => {
stopPolling();
},
onError: () => {
countRef.value += 1;
},
onSuccess: () => {
countRef.value = 0;
},
onFinally: () => {
if (pollingErrorRetryCount === -1 || pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount) {
timeouter = setTimeout(() => {
if (!pollingWhenHidden && !isDocumentVisible()) {
unsubscribeRef.value = subscribeReVisible(() => {
fetchInstance.refresh();
});
} else {
fetchInstance.refresh();
}
}, unref(pollingInterval));
} else {
countRef.value = 0;
}
},
onCancel: () => {
stopPolling();
}
};
};
export {
usePollingPlugin as default
};