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