Open History to see the last commit
1import { noop } from '../core/utils'
2import { PersistedClient, Persistor } from '../persistQueryClient-experimental'
3β
4interface CreateLocalStoragePersistorOptions {
5 /** The key to use when storing the cache to localstorage */
6 localStorageKey?: string
7 /** To avoid localstorage spamming,
8 * pass a time in ms to throttle saving the cache to disk */
9 throttleTime?: number
10}
11β
12export function createLocalStoragePersistor({
13 localStorageKey = `REACT_QUERY_OFFLINE_CACHE`,
14 throttleTime = 1000,
15}: CreateLocalStoragePersistorOptions = {}): Persistor {
16 if (typeof localStorage !== 'undefined') {
17 return {
18 persistClient: throttle(persistedClient => {
19 localStorage.setItem(localStorageKey, JSON.stringify(persistedClient))
20 }, throttleTime),
21 restoreClient: () => {
22 const cacheString = localStorage.getItem(localStorageKey)
23β
24 if (!cacheString) {
25 return
26 }
27β
28 return JSON.parse(cacheString) as PersistedClient
29 },
30 removeClient: () => {
31 localStorage.removeItem(localStorageKey)
32 },
33 }
34 }
35β
36 return {
37 persistClient: noop,
38 restoreClient: noop,
39 removeClient: noop,
40 }
41}
42β
43function throttle<TArgs extends any[]>(
44 func: (...args: TArgs) => any,
45 wait = 100
46) {
47 let timer: number | null = null
48β
49 return function (...args: TArgs) {
50 if (timer === null) {
51 timer = setTimeout(() => {
52 func(...args)
53 timer = null
54 }, wait)
55 }
56 }
57}