Open History to see the last commit
1import { timeoutManager } from '@tanstack/query-core'
2import { noop } from './utils'
3import type { ManagedTimerId } from '@tanstack/query-core'
4import type {
5 PersistRetryer,
6 PersistedClient,
7 Persister,
8} from '@tanstack/query-persist-client-core'
9β
10interface Storage {
11 getItem: (key: string) => string | null
12 setItem: (key: string, value: string) => void
13 removeItem: (key: string) => void
14}
15β
16interface CreateSyncStoragePersisterOptions {
17 /**
18 * The storage client used for setting and retrieving items from cache. For
19 * SSR pass in `undefined`. Note that window.localStorage can be `null` in
20 * Android WebViews depending on how they are configured.
21 */
22 storage: Storage | undefined | null
23 /** The key to use when storing the cache */
24 key?: string
25 /** To avoid spamming, pass a time in ms to throttle saving the cache to disk */
26 throttleTime?: number
27 /**
28 * How to serialize the data to storage.
29 *
30 * @default `JSON.stringify`
31 */
32 serialize?: (client: PersistedClient) => string
33 /**
34 * How to deserialize the data from storage.
35 *
36 * @default `JSON.parse`
37 */
38 deserialize?: (cachedString: string) => PersistedClient
39β
40 retry?: PersistRetryer
41}
42β
43/**
44 * Creates a persister that stores the client in a synchronous storage such as
45 * `window.localStorage`.
46 *
47 * @deprecated use `createAsyncStoragePersister` from
48 * `@tanstack/query-async-storage-persister` instead.
49 * @param options - The `storage` to persist to, the `key`, `throttleTime`,
50 * `serialize`, `deserialize`, and `retry` options.
51 * @returns A persister that saves, restores, and removes the client in
52 * `storage`. Without `storage`, its methods do nothing.
53 */
54export function createSyncStoragePersister({
55 storage,
56 key = `REACT_QUERY_OFFLINE_CACHE`,
57 throttleTime = 1000,
58 serialize = JSON.stringify,
59 deserialize = JSON.parse,
60 retry,
61}: CreateSyncStoragePersisterOptions): Persister {
62 if (storage) {
63 const trySave = (persistedClient: PersistedClient): Error | undefined => {
64 try {
65 storage.setItem(key, serialize(persistedClient))
66 return
67 } catch (error) {
68 return error as Error
69 }
70 }
71 return {
72 persistClient: throttle((persistedClient) => {
73 let client: PersistedClient | undefined = persistedClient
74 let error = trySave(client)
75 let errorCount = 0
76 while (error && client) {
77 errorCount++
78 client = retry?.({
79 persistedClient: client,
80 error,
81 errorCount,
82 })
83β
84 if (client) {
85 error = trySave(client)
86 }
87 }
88 }, throttleTime),
89 restoreClient: () => {
90 const cacheString = storage.getItem(key)
91β
92 if (!cacheString) {
93 return
94 }
95β
96 return deserialize(cacheString)
97 },
98 removeClient: () => {
99 storage.removeItem(key)
100 },
101 }
102 }
103β
104 return {
105 persistClient: noop,
106 restoreClient: noop,
107 removeClient: noop,
108 }
109}
110β
111/**
112 * Wraps a function so it runs at most once per `wait` milliseconds, with the
113 * arguments of the latest call.
114 *
115 * @param func - The function to throttle.
116 * @param wait - The time to wait before running `func`, in milliseconds.
117 * @returns The throttled function.
118 */
119function throttle<TArgs extends Array<any>>(
120 func: (...args: TArgs) => any,
121 wait = 100,
122) {
123 let timer: ManagedTimerId | null = null
124 let params: TArgs
125 return function (...args: TArgs) {
126 params = args
127 if (timer === null) {
128 timer = timeoutManager.setTimeout(() => {
129 func(...params)
130 timer = null
131 }, wait)
132 }
133 }
134}