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