@hazae41/glacier
Version:
Yet another React data (re)fetching library
47 lines (43 loc) • 1.47 kB
JavaScript
var react = require('react');
/**
* Retry request on error using exponential backoff
* @see useInterval for interval based requests
* @param query
* @param settings
* @param options.init Initial timeout to be multiplied (in milliseconds)
* @param options.base Exponent base (2 means the next timeout will be 2 times longer)
* @param options.max Maximum count (3 means do not retry after 3 retries)
* @see https://en.wikipedia.org/wiki/Exponential_backoff
* @see https://en.wikipedia.org/wiki/Geometric_progression
*/
function useRetry(query, settings = {}) {
const { fetcher, ready, cacheKey, fetchOrThrow: fetch, error } = query;
const { init = 1000, base = 2, max = 3 } = settings;
const count = react.useRef(0);
react.useMemo(() => {
count.current = 0;
}, [cacheKey]);
react.useEffect(() => {
if (!ready)
return;
if (fetcher == null)
return;
if (error == null) {
count.current = 0;
return;
}
if (count.current >= max)
return;
const ratio = base ** count.current;
function f() {
count.current++;
// TODO use suspend or wait cooldown
fetch().catch(console.warn);
}
const t = setTimeout(f, init * ratio);
return () => clearTimeout(t);
}, [ready, error, fetch]);
}
exports.useRetry = useRetry;
//# sourceMappingURL=use-retry.cjs.map
;