UNPKG

@td-design/rn-hooks

Version:

从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率

50 lines (47 loc) 1.7 kB
import { useRef } from 'react'; import useUpdateEffect from '../../useUpdateEffect/index.js'; var usePollingPlugin = function (fetchInstance, _a) { var pollingInterval = _a.pollingInterval, _b = _a.pollingErrorRetryCount, pollingErrorRetryCount = _b === void 0 ? -1 : _b; var timerRef = useRef(); var countRef = useRef(0); var stopPolling = function () { if (timerRef.current) { clearTimeout(timerRef.current); } }; useUpdateEffect(function () { if (!pollingInterval) { stopPolling(); } }, [pollingInterval]); if (!pollingInterval) return {}; return { onBefore: function () { stopPolling(); }, onError: function () { countRef.current += 1; }, onSuccess: function () { countRef.current = 0; }, onFinally: function () { if (pollingErrorRetryCount === -1 || // When an error occurs, the request is not repeated after pollingErrorRetryCount retries (pollingErrorRetryCount !== -1 && countRef.current <= pollingErrorRetryCount)) { // 之所以用setTimeout, 是因为fetchInstance.refresh()最后都会走到onFinally,然后这里又会再次调用refresh,从而实现跟interval一样的效果 timerRef.current = setTimeout(function () { fetchInstance.refresh(); }, pollingInterval); } else { countRef.current = 0; } }, onCancel: function () { stopPolling(); }, }; }; export { usePollingPlugin };