@taro-hooks/use-request
Version:
useRequest hook for Taro
51 lines • 1.73 kB
JavaScript
import { useRef } from '@taro-hooks/core';
import { useUpdateEffect } from '@taro-hooks/ahooks';
import { escapeState } from '@taro-hooks/shared';
import useVisible from '../useVisible';
import subscribeReVisible from '../utils/subscribeReVisible';
var usePollingPlugin = function usePollingPlugin(fetchInstance, _ref) {
var pollingInterval = _ref.pollingInterval,
_ref$pollingWhenHidde = _ref.pollingWhenHidden,
pollingWhenHidden = _ref$pollingWhenHidde === void 0 ? true : _ref$pollingWhenHidde;
var timerRef = useRef();
var unsubscribeRef = useRef();
var documentVisible = useVisible();
var unsubscribeReVisible = subscribeReVisible(function () {
if (!pollingWhenHidden && !escapeState(documentVisible)) {
fetchInstance.refresh();
}
});
var stopPolling = function stopPolling() {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
unsubscribeRef.current == null ? void 0 : unsubscribeRef.current();
};
useUpdateEffect(function () {
if (!pollingInterval) {
stopPolling();
}
}, [pollingInterval]);
if (!pollingInterval) {
return {};
}
return {
onBefore: function onBefore() {
stopPolling();
},
onFinally: function onFinally() {
// if pollingWhenHidden = false && document is hidden, then stop polling and subscribe revisable
if (!pollingWhenHidden && !escapeState(documentVisible) || !pollingInterval) {
unsubscribeRef.current = unsubscribeReVisible;
return;
}
timerRef.current = setTimeout(function () {
fetchInstance.refresh();
}, pollingInterval);
},
onCancel: function onCancel() {
stopPolling();
}
};
};
export default usePollingPlugin;