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

createPersister.md

135 lines4.9 KB

1---
2id: createPersister
3title: experimental_createPersister
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```bash
11npm install @tanstack/query-persist-client-core
12```
13​
14or
15​
16```bash
17pnpm add @tanstack/query-persist-client-core
18```
19​
20or
21​
22```bash
23yarn add @tanstack/query-persist-client-core
24```
25​
26or
27​
28```bash
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_createPersister` function
37- Create a new `experimental_createPersister`
38 - you can pass any `storage` to it that adheres to the `AsyncStorage` or `Storage` 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_createPersister } from '@tanstack/query-persist-client-core'
52​
53const queryClient = new QueryClient({
54 defaultOptions: {
55 queries: {
56 gcTime: 1000 * 30, // 30 seconds
57 persister: experimental_createPersister({
58 storage: AsyncStorage,
59 maxAge: 1000 * 60 * 60 * 12, // 12 hours
60 }),
61 },
62 },
63})
64```
65​
66### Adapted defaults
67​
68The `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.
69​
70## API
71​
72### `experimental_createPersister`
73​
74```tsx
75experimental_createPersister(options: StoragePersisterOptions)
76```
77​
78#### `Options`
79​
80```tsx
81export interface StoragePersisterOptions {
82 /** The storage client used for setting and retrieving items from cache.
83 * For SSR pass in `undefined`.
84 */
85 storage: AsyncStorage | Storage | undefined | null
86 /**
87 * How to serialize the data to storage.
88 * @default `JSON.stringify`
89 */
90 serialize?: (persistedQuery: PersistedQuery) => string
91 /**
92 * How to deserialize the data from storage.
93 * @default `JSON.parse`
94 */
95 deserialize?: (cachedString: string) => PersistedQuery
96 /**
97 * A unique string that can be used to forcefully invalidate existing caches,
98 * if they do not share the same buster string
99 */
100 buster?: string
101 /**
102 * The max-allowed age of the cache in milliseconds.
103 * If a persisted cache is found that is older than this
104 * time, it will be discarded
105 * @default 24 hours
106 */
107 maxAge?: number
108 /**
109 * Prefix to be used for storage key.
110 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
111 */
112 prefix?: string
113 /**
114 * Filters to narrow down which Queries should be persisted.
115 */
116 filters?: QueryFilters
118​
119interface AsyncStorage {
120 getItem: (key: string) => Promise<string | undefined | null>
121 setItem: (key: string, value: string) => Promise<unknown>
122 removeItem: (key: string) => Promise<void>
124```
125​
126The default options are:
127​
128```tsx
130 prefix = 'tanstack-query',
131 maxAge = 1000 * 60 * 60 * 24,
132 serialize = JSON.stringify,
133 deserialize = JSON.parse,
135```