Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.ts

53 lines1.5 KB

1import { PersistedClient, Persister } from '../persistQueryClient'
2import { asyncThrottle } from './asyncThrottle'
3​
4interface AsyncStorage {
5 getItem: (key: string) => Promise<string | null>
6 setItem: (key: string, value: string) => Promise<void>
7 removeItem: (key: string) => Promise<void>
8}
9​
10interface CreateAsyncStoragePersisterOptions {
11 /** The storage client used for setting an retrieving items from cache */
12 storage: AsyncStorage
13 /** The key to use when storing the cache */
14 key?: string
15 /** To avoid spamming,
16 * pass a time in ms to throttle saving the cache to disk */
17 throttleTime?: number
18 /**
19 * How to serialize the data to storage.
20 * @default `JSON.stringify`
21 */
22 serialize?: (client: PersistedClient) => string
23 /**
24 * How to deserialize the data from storage.
25 * @default `JSON.parse`
26 */
27 deserialize?: (cachedString: string) => PersistedClient
29​
30export const createAsyncStoragePersister = ({
31 storage,
32 key = `REACT_QUERY_OFFLINE_CACHE`,
33 throttleTime = 1000,
34 serialize = JSON.stringify,
35 deserialize = JSON.parse,
36}: CreateAsyncStoragePersisterOptions): Persister => {
37 return {
38 persistClient: asyncThrottle(
39 persistedClient => storage.setItem(key, serialize(persistedClient)),
40 { interval: throttleTime }
41 ),
42 restoreClient: async () => {
43 const cacheString = await storage.getItem(key)
44​
45 if (!cacheString) {
46 return
47 }
48​
49 return deserialize(cacheString) as PersistedClient
50 },
51 removeClient: () => storage.removeItem(key),
52 }