UNPKG

@td-design/rn-hooks

Version:

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

52 lines (48 loc) 1.72 kB
'use strict'; var react = require('react'); var index = require('../../useUpdateEffect/index.js'); var usePollingPlugin = function (fetchInstance, _a) { var pollingInterval = _a.pollingInterval, _b = _a.pollingErrorRetryCount, pollingErrorRetryCount = _b === void 0 ? -1 : _b; var timerRef = react.useRef(); var countRef = react.useRef(0); var stopPolling = function () { if (timerRef.current) { clearTimeout(timerRef.current); } }; index(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(); }, }; }; exports.usePollingPlugin = usePollingPlugin;