UNPKG

react-query

Version:

Hooks for managing, caching and syncing asynchronous and remote data in React

92 lines (77 loc) 2.46 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactQueryCreateAsyncStoragePersister = {})); })(this, (function (exports) { 'use strict'; const noop = () => { /* do nothing */ }; function asyncThrottle(func, { interval = 1000, onError = noop } = {}) { if (typeof func !== 'function') throw new Error('argument is not function.'); let running = false; let lastTime = 0; let timeout; let currentArgs = null; const execFunc = async () => { if (currentArgs) { const args = currentArgs; currentArgs = null; try { running = true; await func(...args); } catch (error) { onError(error); } finally { lastTime = Date.now(); // this line must after 'func' executed to avoid two 'func' running in concurrent. running = false; } } }; const delayFunc = async () => { clearTimeout(timeout); timeout = setTimeout(() => { if (running) { delayFunc(); // Will come here when 'func' execution time is greater than the interval. } else { execFunc(); } }, interval); }; return (...args) => { currentArgs = args; const tooSoon = Date.now() - lastTime < interval; if (running || tooSoon) { delayFunc(); } else { execFunc(); } }; } const createAsyncStoragePersister = ({ storage, key = "REACT_QUERY_OFFLINE_CACHE", throttleTime = 1000, serialize = JSON.stringify, deserialize = JSON.parse }) => { return { persistClient: asyncThrottle(persistedClient => storage.setItem(key, serialize(persistedClient)), { interval: throttleTime }), restoreClient: async () => { const cacheString = await storage.getItem(key); if (!cacheString) { return; } return deserialize(cacheString); }, removeClient: () => storage.removeItem(key) }; }; exports.createAsyncStoragePersister = createAsyncStoragePersister; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=createAsyncStoragePersister.development.js.map