Open History to see the last commit
1import { noop } from './utils'
2import type {
3 PersistRetryer,
4 PersistedClient,
5 Persister,
6} from '@tanstack/query-persist-client-core'
7β
8interface Storage {
9 getItem: (key: string) => string | null
10 setItem: (key: string, value: string) => void
11 removeItem: (key: string) => void
12}
13β
14interface CreateSyncStoragePersisterOptions {
15 /** The storage client used for setting and retrieving items from cache.
16 * For SSR pass in `undefined`. Note that window.localStorage can be
17 * `null` in Android WebViews depending on how they are configured.
18 */
19 storage: Storage | undefined | null
20 /** The key to use when storing the cache */
21 key?: string
22 /** To avoid spamming,
23 * pass a time in ms to throttle saving the cache to disk */
24 throttleTime?: number
25 /**
26 * How to serialize the data to storage.
27 * @default `JSON.stringify`
28 */
29 serialize?: (client: PersistedClient) => string
30 /**
31 * How to deserialize the data from storage.
32 * @default `JSON.parse`
33 */
34 deserialize?: (cachedString: string) => PersistedClient
35β
36 retry?: PersistRetryer
37}
38β
39export function createSyncStoragePersister({
40 storage,
41 key = `REACT_QUERY_OFFLINE_CACHE`,
42 throttleTime = 1000,
43 serialize = JSON.stringify,
44 deserialize = JSON.parse,
45 retry,
46}: CreateSyncStoragePersisterOptions): Persister {
47 if (storage) {
48 const trySave = (persistedClient: PersistedClient): Error | undefined => {
49 try {
50 storage.setItem(key, serialize(persistedClient))
51 return
52 } catch (error) {
53 return error as Error
54 }
55 }
56 return {
57 persistClient: throttle((persistedClient) => {
58 let client: PersistedClient | undefined = persistedClient
59 let error = trySave(client)
60 let errorCount = 0
61 while (error && client) {
62 errorCount++
63 client = retry?.({
64 persistedClient: client,
65 error,
66 errorCount,
67 })
68β
69 if (client) {
70 error = trySave(client)
71 }
72 }
73 }, throttleTime),
74 restoreClient: () => {
75 const cacheString = storage.getItem(key)
76β
77 if (!cacheString) {
78 return
79 }
80β
81 return deserialize(cacheString)
82 },
83 removeClient: () => {
84 storage.removeItem(key)
85 },
86 }
87 }
88β
89 return {
90 persistClient: noop,
91 restoreClient: () => undefined,
92 removeClient: noop,
93 }
94}
95β
96function throttle<TArgs extends Array<any>>(
97 func: (...args: TArgs) => any,
98 wait = 100,
99) {
100 let timer: ReturnType<typeof setTimeout> | null = null
101 let params: TArgs
102 return function (...args: TArgs) {
103 params = args
104 if (timer === null) {
105 timer = setTimeout(() => {
106 func(...params)
107 timer = null
108 }, wait)
109 }
110 }
111}