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

createPersister.md

215 lines8.3 KB

1---
2id: createPersister
3title: experimental_createQueryPersister
4---
5​
6## Installation
7​
8This utility comes as a separate package and is available under the `'@tanstack/query-persist-client-core'` import.
9​
10```sh
11npm install @tanstack/query-persist-client-core
12```
13​
14or
15​
16```sh
17pnpm add @tanstack/query-persist-client-core
18```
19​
20or
21​
22```sh
23yarn add @tanstack/query-persist-client-core
24```
25​
26or
27​
28```sh
29bun add @tanstack/query-persist-client-core
30```
31​
32## Usage
33​
34- Import the `experimental_createQueryPersister` function
35- Create a new `experimental_createQueryPersister`
36 - you can pass any `storage` to it that adheres to the `AsyncStorage` interface
37- Pass that `persister` as an option to your Query. This can be done either by passing it to the `defaultOptions` of the `QueryClient` or to any `useQuery` hook instance.
38 - If you pass this `persister` as `defaultOptions`, all queries will be persisted to the provided `storage`. You can additionally narrow this down by passing `filters`. In contrast to the `persistClient` plugin, this will not persist the whole query client as a single item, but each query separately. As a key, the query hash is used.
39 - If you provide this `persister` to a single `useQuery` hook, only this Query will be persisted.
40- Note: `queryClient.setQueryData()` operations are not persisted, this means that if you perform an optimistic update and refresh the page before the query has been invalidated, your changes to the query data will be lost. See https://github.com/TanStack/query/issues/6310
41​
42This way, you do not need to store whole `QueryClient`, but choose what is worth to be persisted in your application. Each query is lazily restored (when the Query is first used) and persisted (after each run of the `queryFn`), so it does not need to be throttled. `staleTime` is also respected after restoring the Query, so if data is considered `stale`, it will be refetched immediately after restoring. If data is `fresh`, the `queryFn` will not run.
43​
44Garbage collecting a Query from memory **does not** affect the persisted data. That means Queries can be kept in memory for a shorter period of time to be more **memory efficient**. If they are used the next time, they will just be restored from the persistent storage again.
45​
46```tsx
47import { QueryClient } from '@tanstack/vue-query'
48import { experimental_createQueryPersister } from '@tanstack/query-persist-client-core'
49​
50const persister = experimental_createQueryPersister({
51 storage: localStorage,
52 maxAge: 1000 * 60 * 60 * 12, // 12 hours
53})
54​
55const queryClient = new QueryClient({
56 defaultOptions: {
57 queries: {
58 gcTime: 1000 * 30, // 30 seconds
59 persister: persister.persisterFn,
60 },
61 },
62})
63```
64​
65### Adapted defaults
66​
67The `createPersister` plugin technically wraps the `queryFn`, so it doesn't restore if the `queryFn` doesn't run. In that way, it acts as a caching layer between the Query and the network. Thus, the `networkMode` defaults to `'offlineFirst'` when a persister is used, so that restoring from the persistent storage can also happen even if there is no network connection.
68​
69## Additional utilities
70​
71Invoking `experimental_createQueryPersister` returns additional utilities in addition to `persisterFn` for easier implementation of userland functionalities.
72​
73### `persistQueryByKey(queryKey: QueryKey, queryClient: QueryClient): Promise<void>`
74​
75This function will persist `Query` to storage and key defined when creating persister.
76This utility might be used along `setQueryData` to persist optimistic update to storage without waiting for invalidation.
77​
78```tsx
79const persister = experimental_createQueryPersister({
80 storage: localStorage,
81 maxAge: 1000 * 60 * 60 * 12, // 12 hours
82})
83​
84const queryClient = useQueryClient()
85​
86useMutation({
87 mutationFn: updateTodo,
88 onMutate: async (newTodo) => {
89 ...
90 // Optimistically update to the new value
91 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
92 // And persist it to storage
93 persister.persistQueryByKey(['todos'], queryClient)
94 ...
95 },
96})
97```
98​
99### `retrieveQuery<T>(queryHash: string): Promise<T | undefined>`
100​
101This function would attempt to retrieve persisted query by `queryHash`.
102If `query` is `expired`, `busted` or `malformed` it would be removed from the storage instead, and `undefined` would be returned.
103​
104### `persisterGc(): Promise<void>`
105​
106This function can be used to sporadically clean up storage from `expired`, `busted` or `malformed` entries.
107​
108For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
109For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
110​
111### `restoreQueries(queryClient: QueryClient, filters): Promise<void>`
112​
113This function can be used to restore queries that are currently stored by persister.
114For example when your app is starting up in offline mode, or you want all or only specific data from previous session to be immediately available without intermediate `loading` state.
115​
116The filter object supports the following properties:
117​
118- `queryKey?: QueryKey`
119 - Set this property to define a query key to match on.
120- `exact?: boolean`
121 - If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed.
122​
123For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
124For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
125​
126### `removeQueries(filters): Promise<void>`
127​
128When using `queryClient.removeQueries`, the data remains in the persister and needs to be removed separately.
129This function can be used to remove queries that are currently stored by persister.
130​
131The filter object supports the following properties:
132​
133- `queryKey?: QueryKey`
134 - Set this property to define a query key to match on.
135- `exact?: boolean`
136 - If you don't want to search queries inclusively by query key, you can pass the `exact: true` option to return only the query with the exact query key you have passed.
137​
138For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
139For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
140​
141## API
142​
143### `experimental_createQueryPersister`
144​
145```tsx
146experimental_createQueryPersister(options: StoragePersisterOptions)
147```
148​
149#### `Options`
150​
151```tsx
152export interface StoragePersisterOptions {
153 /** The storage client used for setting and retrieving items from cache.
154 * For SSR pass in `undefined`.
155 */
156 storage: AsyncStorage | Storage | undefined | null
157 /**
158 * How to serialize the data to storage.
159 * @default `JSON.stringify`
160 */
161 serialize?: (persistedQuery: PersistedQuery) => string
162 /**
163 * How to deserialize the data from storage.
164 * @default `JSON.parse`
165 */
166 deserialize?: (cachedString: string) => PersistedQuery
167 /**
168 * A unique string that can be used to forcefully invalidate existing caches,
169 * if they do not share the same buster string
170 */
171 buster?: string
172 /**
173 * The max-allowed age of the cache in milliseconds.
174 * If a persisted cache is found that is older than this
175 * time, it will be discarded
176 * @default 24 hours
177 */
178 maxAge?: number
179 /**
180 * Prefix to be used for storage key.
181 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
182 */
183 prefix?: string
184 /**
185 * If set to `true`, the query will refetch on successful query restoration if the data is stale.
186 * If set to `false`, the query will not refetch on successful query restoration.
187 * If set to `'always'`, the query will always refetch on successful query restoration.
188 * Defaults to `true`.
189 */
190 refetchOnRestore?: boolean | 'always'
191 /**
192 * Filters to narrow down which Queries should be persisted.
193 */
194 filters?: QueryFilters
196​
197interface AsyncStorage<TStorageValue = string> {
198 getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>
199 setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>
200 removeItem: (key: string) => MaybePromise<void>
201 entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>
203```
204​
205The default options are:
206​
207```tsx
209 prefix = 'tanstack-query',
210 maxAge = 1000 * 60 * 60 * 24,
211 serialize = JSON.stringify,
212 deserialize = JSON.parse,
213 refetchOnRestore = true,
215```