UNPKG

ahooks

Version:
60 lines (59 loc) 2.13 kB
import { useRef } from 'react'; import useUpdateEffect from '../../../useUpdateEffect'; import isDocumentVisible from '../utils/isDocumentVisible'; import subscribeReVisible from '../utils/subscribeReVisible'; const usePollingPlugin = (fetchInstance, { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 }) => { const timerRef = useRef(undefined); const unsubscribeRef = useRef(undefined); const countRef = useRef(0); const stopPolling = () => { var _a; if (timerRef.current) { clearTimeout(timerRef.current); } (_a = unsubscribeRef.current) === null || _a === void 0 ? void 0 : _a.call(unsubscribeRef); }; useUpdateEffect(() => { if (!pollingInterval) { stopPolling(); } }, [pollingInterval]); if (!pollingInterval) { return {}; } return { onBefore: () => { stopPolling(); }, onError: () => { countRef.current += 1; }, onSuccess: () => { countRef.current = 0; }, onFinally: () => { if (pollingErrorRetryCount === -1 || // When an error occurs, the request is not repeated after pollingErrorRetryCount retries (pollingErrorRetryCount !== -1 && countRef.current <= pollingErrorRetryCount)) { timerRef.current = setTimeout(() => { // if pollingWhenHidden = false && document is hidden, then stop polling and subscribe revisible if (!pollingWhenHidden && !isDocumentVisible()) { unsubscribeRef.current = subscribeReVisible(() => { fetchInstance.refresh(); }); } else { fetchInstance.refresh(); } }, pollingInterval); } else { countRef.current = 0; } }, onCancel: () => { stopPolling(); }, }; }; export default usePollingPlugin;