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

createPersister.md

220 lines8.9 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> Note: This util is also included in the `@tanstack/react-query-persist-client` package, so you do not need to install it separately if you are using that package.
33​
34## Usage
35​
36- Import the `experimental_createQueryPersister` function
37- Create a new `experimental_createQueryPersister`
38 - you can pass any `storage` to it that adheres to the `AsyncStorage` interface - the example below uses the async-storage from React Native.
39- 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.
40 - 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.
41 - If you provide this `persister` to a single `useQuery` hook, only this Query will be persisted.
42- 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
43​
44This 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.
45​
46Garbage 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.
47​
48```tsx
49import AsyncStorage from '@react-native-async-storage/async-storage'
50import { QueryClient } from '@tanstack/react-query'
51import { experimental_createQueryPersister } from '@tanstack/query-persist-client-core'
52​
53const persister = experimental_createQueryPersister({
54 storage: AsyncStorage,
55 maxAge: 12 * 60 * 60 * 1000, // 12 hours
56})
57​
58const queryClient = new QueryClient({
59 defaultOptions: {
60 queries: {
61 gcTime: 30 * 1000, // 30 seconds
62 persister: persister.persisterFn,
63 },
64 },
65})
66```
67​
68### Adapted defaults
69​
70The `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.
71​
72## Additional utilities
73​
74Invoking `experimental_createQueryPersister` returns additional utilities in addition to `persisterFn` for easier implementation of userland functionalities.
75​
76### `persistQueryByKey(queryKey: QueryKey, queryClient: QueryClient): Promise<void>`
77​
78This function will persist `Query` to storage and key defined when creating persister.
79This utility might be used along `setQueryData` to persist optimistic update to storage without waiting for invalidation.
80​
81```tsx
82const persister = experimental_createQueryPersister({
83 storage: AsyncStorage,
84 maxAge: 12 * 60 * 60 * 1000, // 12 hours
85})
86​
87const queryClient = useQueryClient()
88​
89useMutation({
90 mutationFn: updateTodo,
91 onMutate: async (newTodo) => {
92 ...
93 // Optimistically update to the new value
94 queryClient.setQueryData(['todos'], (old) => [...old, newTodo])
95 // And persist it to storage
96 persister.persistQueryByKey(['todos'], queryClient)
97 ...
98 },
99})
100```
101​
102### `retrieveQuery<T>(queryHash: string): Promise<T | undefined>`
103​
104This function would attempt to retrieve persisted query by `queryHash`.
105If `query` is `expired`, `busted` or `malformed` it would be removed from the storage instead, and `undefined` would be returned.
106​
107Persisted entries must have a string `queryHash`, an array `queryKey`, and a `state` object with a finite numeric `dataUpdatedAt`. Entries that do not meet these requirements are removed during retrieval, garbage collection, restoration, and filtered removal, without interrupting processing of other entries. `null` remains valid query data.
108​
109### `persisterGc(): Promise<void>`
110​
111This function can be used to sporadically clean up storage from `expired`, `busted` or `malformed` entries.
112​
113For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
114For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
115​
116### `restoreQueries(queryClient: QueryClient, filters): Promise<void>`
117​
118This function can be used to restore queries that are currently stored by persister.
119For 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.
120​
121The filter object supports the following properties:
122​
123- `queryKey?: QueryKey`
124 - Set this property to define a query key to match on.
125- `exact?: boolean`
126 - 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.
127​
128For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
129For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
130​
131### `removeQueries(filters): Promise<void>`
132​
133When using `queryClient.removeQueries`, the data remains in the persister and needs to be removed separately.
134This function can be used to remove queries that are currently stored by persister.
135​
136The filter object supports the following properties:
137​
138- `queryKey?: QueryKey`
139 - Set this property to define a query key to match on.
140- `exact?: boolean`
141 - 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.
142​
143For this function to work, your storage must expose `entries` method that would return a `key-value tuple array`.
144For example `Object.entries(localStorage)` for `localStorage` or `entries` from `idb-keyval`.
145​
146## API
147​
148### `experimental_createQueryPersister`
149​
150```tsx
151experimental_createQueryPersister(options: StoragePersisterOptions)
152```
153​
154#### `Options`
155​
156```tsx
157export interface StoragePersisterOptions {
158 /** The storage client used for setting and retrieving items from cache.
159 * For SSR pass in `undefined`.
160 */
161 storage: AsyncStorage | Storage | undefined | null
162 /**
163 * How to serialize the data to storage.
164 * @default `JSON.stringify`
165 */
166 serialize?: (persistedQuery: PersistedQuery) => string
167 /**
168 * How to deserialize the data from storage.
169 * @default `JSON.parse`
170 */
171 deserialize?: (cachedString: string) => PersistedQuery
172 /**
173 * A unique string that can be used to forcefully invalidate existing caches,
174 * if they do not share the same buster string
175 */
176 buster?: string
177 /**
178 * The max-allowed age of the cache in milliseconds.
179 * If a persisted cache is found that is older than this
180 * time, it will be discarded
181 * @default 24 hours
182 */
183 maxAge?: number
184 /**
185 * Prefix to be used for storage key.
186 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
187 */
188 prefix?: string
189 /**
190 * If set to `true`, the query will refetch on successful query restoration if the data is stale.
191 * If set to `false`, the query will not refetch on successful query restoration.
192 * If set to `'always'`, the query will always refetch on successful query restoration.
193 * Defaults to `true`.
194 */
195 refetchOnRestore?: boolean | 'always'
196 /**
197 * Filters to narrow down which Queries should be persisted.
198 */
199 filters?: QueryFilters
201​
202interface AsyncStorage<TStorageValue = string> {
203 getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>
204 setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>
205 removeItem: (key: string) => MaybePromise<void>
206 entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>
208```
209​
210The default options are:
211​
212```tsx
214 prefix = 'tanstack-query',
215 maxAge = 24 * 60 * 60 * 1000,
216 serialize = JSON.stringify,
217 deserialize = JSON.parse,
218 refetchOnRestore = true,
220```