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

persistQueryClient.md

285 lines10.0 KB

1---
2id: persistQueryClient
3title: persistQueryClient
4---
5​
6This is set of utilities for interacting with "persisters" which save your queryClient for later use. Different **persisters** can be used to store your client and cache to many different storage layers.
7​
8## Build Persisters
9​
10- [createSyncStoragePersister](../createSyncStoragePersister)
11- [createAsyncStoragePersister](../createAsyncStoragePersister)
12- [create a custom persister](#persisters)
13​
14## How It Works
15​
16**IMPORTANT** - for persist to work properly, you probably want to pass `QueryClient` a `cacheTime` value to override the default during hydration (as shown above).
17​
18If it is not set when creating the `QueryClient` instance, it will default to `300000` (5 minutes) for hydration, and the stored cache will be discarded after 5 minutes of inactivity. This is the default garbage collection behavior.
19​
20It should be set as the same value or higher than persistQueryClient's `maxAge` option. E.g. if `maxAge` is 24 hours (the default) then `cacheTime` should be 24 hours or higher. If lower than `maxAge`, garbage collection will kick in and discard the stored cache earlier than expected.
21​
22You can also pass it `Infinity` to disable garbage collection behavior entirely.
23​
24```tsx
25const queryClient = new QueryClient({
26 defaultOptions: {
27 queries: {
28 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
29 },
30 },
31})
32```
33​
34### Cache Busting
35​
36Sometimes you may make changes to your application or data that immediately invalidate any and all cached data. If and when this happens, you can pass a `buster` string option. If the cache that is found does not also have that buster string, it will be discarded. The following several functions accept this option:
37​
38```tsx
39persistQueryClient({ queryClient, persister, buster: buildHash })
40persistQueryClientSave({ queryClient, persister, buster: buildHash })
41persistQueryClientRestore({ queryClient, persister, buster: buildHash })
42```
43​
44### Removal
45​
46If data is found to be any of the following:
47​
481. expired (see `maxAge`)
492. busted (see `buster`)
503. error (ex: `throws ...`)
514. empty (ex: `undefined`)
52​
53the persister `removeClient()` is called and the cache is immediately discarded.
54​
55## API
56​
57### `persistQueryClientSave`
58​
59- Your query/mutation are [`dehydrated`](../../reference/hydration#dehydrate) and stored by the persister you provided.
60- `createSyncStoragePersister` and `createAsyncStoragePersister` throttle this action to happen at most every 1 second to save on potentially expensive writes. Review their documentation to see how to customize their throttle timing.
61​
62You can use this to explicitly persist the cache at the moment(s) you choose.
63​
64```tsx
65persistQueryClientSave({
66 queryClient,
67 persister,
68 buster: '',
69 dehydrateOptions: undefined,
70})
71```
72​
73### `persistQueryClientSubscribe`
74​
75Runs `persistQueryClientSave` whenever the cache changes for your `queryClient`. For example: you might initiate the `subscribe` when a user logs-in and checks "Remember me".
76​
77- It returns an `unsubscribe` function which you can use to discontinue the monitor; ending the updates to the persisted cache.
78- If you want to erase the persisted cache after the `unsubscribe`, you can send a new `buster` to `persistQueryClientRestore` which will trigger the persister's `removeClient` function and discard the persisted cache.
79​
80```tsx
81persistQueryClientSubscribe({
82 queryClient,
83 persister,
84 buster: '',
85 dehydrateOptions: undefined,
86})
87```
88​
89### `persistQueryClientRestore`
90​
91- Attempts to [`hydrate`](../../reference/hydration#hydrate) a previously persisted dehydrated query/mutation cache from the persister back into the query cache of the passed query client.
92- If a cache is found that is older than the `maxAge` (which by default is 24 hours), it will be discarded. This timing can be customized as you see fit.
93​
94You can use this to restore the cache at moment(s) you choose.
95​
96```tsx
97persistQueryClientRestore({
98 queryClient,
99 persister,
100 maxAge: 1000 * 60 * 60 * 24, // 24 hours
101 buster: '',
102 hydrateOptions: undefined,
103})
104```
105​
106### `persistQueryClient`
107​
108Takes the following actions:
109​
1101. Immediately restores any persisted cache ([see `persistQueryClientRestore`](#persistqueryclientrestore))
1112. Subscribes to the query cache and returns the `unsubscribe` function ([see `persistQueryClientSubscribe`](#persistqueryclientsubscribe)).
112​
113This functionality is preserved from version 3.x.
114​
115```tsx
116persistQueryClient({
117 queryClient,
118 persister,
119 maxAge: 1000 * 60 * 60 * 24, // 24 hours
120 buster: '',
121 hydrateOptions: undefined,
122 dehydrateOptions: undefined,
123})
124```
125​
126### `Options`
127​
128All options available are as follows:
129​
130```tsx
131interface PersistQueryClientOptions {
132 /** The QueryClient to persist */
133 queryClient: QueryClient
134 /** The Persister interface for storing and restoring the cache
135 * to/from a persisted location */
136 persister: Persister
137 /** The max-allowed age of the cache in milliseconds.
138 * If a persisted cache is found that is older than this
139 * time, it will be **silently** discarded
140 * (defaults to 24 hours) */
141 maxAge?: number
142 /** A unique string that can be used to forcefully
143 * invalidate existing caches if they do not share the same buster string */
144 buster?: string
145 /** The options passed to the hydrate function
146 * Not used on `persistQueryClientSave` or `persistQueryClientSubscribe` */
147 hydrateOptions?: HydrateOptions
148 /** The options passed to the dehydrate function
149 * Not used on `persistQueryClientRestore` */
150 dehydrateOptions?: DehydrateOptions
152```
153​
154There are actually three interfaces available:
155​
156- `PersistedQueryClientSaveOptions` is used for `persistQueryClientSave` and `persistQueryClientSubscribe` (doesn't use `hydrateOptions`).
157- `PersistedQueryClientRestoreOptions` is used for `persistQueryClientRestore` (doesn't use `dehydrateOptions`).
158- `PersistQueryClientOptions` is used for `persistQueryClient`
159​
160## Usage with React
161​
162[persistQueryClient](#persistQueryClient) will try to restore the cache and automatically subscribes to further changes, thus syncing your client to the provided storage.
163​
164However, restoring is asynchronous, because all persisters are async by nature, which means that if you render your App while you are restoring, you might get into race conditions if a query mounts and fetches at the same time.
165​
166Further, if you subscribe to changes outside of the React component lifecycle, you have no way of unsubscribing:
167​
168```tsx
169// 🚨 never unsubscribes from syncing
170persistQueryClient({
171 queryClient,
172 persister: localStoragePersister,
173})
174​
175// 🚨 happens at the same time as restoring
176ReactDOM.createRoot(rootElement).render(<App />)
177```
178​
179### PersistQueryClientProvider
180​
181For this use-case, you can use the `PersistQueryClientProvider`. It will make sure to subscribe / unsubscribe correctly according to the React component lifecycle, and it will also make sure that queries will not start fetching while we are still restoring. Queries will still render though, they will just be put into `fetchingState: 'idle'` until data has been restored. Then, they will refetch unless the restored data is _fresh_ enough, and _initialData_ will also be respected. It can be used _instead of_ the normal [QueryClientProvider](../../reference/QueryClientProvider):
182​
183```tsx
184import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
185import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
186​
187const queryClient = new QueryClient({
188 defaultOptions: {
189 queries: {
190 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
191 },
192 },
193})
194​
195const persister = createSyncStoragePersister({
196 storage: window.localStorage,
197})
198​
199ReactDOM.createRoot(rootElement).render(
200 <PersistQueryClientProvider
201 client={queryClient}
202 persistOptions={{ persister }}
203 >
204 <App />
205 </PersistQueryClientProvider>,
207```
208​
209#### Props
210​
211`PersistQueryClientProvider` takes the same props as [QueryClientProvider](../../reference/QueryClientProvider), and additionally:
212​
213- `persistOptions: PersistQueryClientOptions`
214 - all [options](#options) you can pass to [persistQueryClient](#persistqueryclient) minus the QueryClient itself
215- `onSuccess?: () => void`
216 - optional
217 - will be called when the initial restore is finished
218 - can be used to [resumePausedMutations](../../../../reference/QueryClient#queryclientresumepausedmutations)
219​
220### useIsRestoring
221​
222If you are using the `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid race conditions between the restore and mounting queries.
223​
224## Persisters
225​
226### Persisters Interface
227​
228Persisters have the following interfaces:
229​
230```tsx
231export interface Persister {
232 persistClient(persistClient: PersistedClient): Promisable<void>
233 restoreClient(): Promisable<PersistedClient | undefined>
234 removeClient(): Promisable<void>
236```
237​
238Persisted Client entries have the following interface:
239​
240```tsx
241export interface PersistedClient {
242 timestamp: number
243 buster: string
244 cacheState: any
246```
247​
248You can import these (to build a persister):
249​
250```tsx
251import {
252 PersistedClient,
253 Persister,
254} from '@tanstack/react-query-persist-client'
255```
256​
257### Building A Persister
258​
259You can persist however you like. Here is an example of how to build an [Indexed DB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) persister. Compared to `Web Storage API`, Indexed DB is faster, stores more than 5MB, and doesn't require serialization. That means it can readily store Javascript native types, such as `Date` and `File`.
260​
261```tsx
262import { get, set, del } from 'idb-keyval'
263import {
264 PersistedClient,
265 Persister,
266} from '@tanstack/react-query-persist-client'
267​
268/**
269 * Creates an Indexed DB persister
270 * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
271 */
272export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
273 return {
274 persistClient: async (client: PersistedClient) => {
275 await set(idbValidKey, client)
276 },
277 restoreClient: async () => {
278 return await get<PersistedClient>(idbValidKey)
279 },
280 removeClient: async () => {
281 await del(idbValidKey)
282 },
283 } as Persister
285```