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

createPersister.md

134 lines4.6 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​
43This 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.
44​
45Garbage 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.
46​
47```tsx
48import AsyncStorage from '@react-native-async-storage/async-storage'
49import { QueryClient } from '@tanstack/react-query'
50import { experimental_createPersister } from '@tanstack/query-persist-client-core'
51​
52const queryClient = new QueryClient({
53 defaultOptions: {
54 queries: {
55 gcTime: 1000 * 30, // 30 seconds
56 persister: experimental_createPersister({
57 storage: AsyncStorage,
58 maxAge: 1000 * 60 * 60 * 12, // 12 hours
59 }),
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## API
70​
71### `experimental_createPersister`
72​
73```tsx
74experimental_createPersister(options: StoragePersisterOptions)
75```
76​
77#### `Options`
78​
79```tsx
80export interface StoragePersisterOptions {
81 /** The storage client used for setting and retrieving items from cache.
82 * For SSR pass in `undefined`.
83 */
84 storage: AsyncStorage | Storage | undefined | null
85 /**
86 * How to serialize the data to storage.
87 * @default `JSON.stringify`
88 */
89 serialize?: (persistedQuery: PersistedQuery) => string
90 /**
91 * How to deserialize the data from storage.
92 * @default `JSON.parse`
93 */
94 deserialize?: (cachedString: string) => PersistedQuery
95 /**
96 * A unique string that can be used to forcefully invalidate existing caches,
97 * if they do not share the same buster string
98 */
99 buster?: string
100 /**
101 * The max-allowed age of the cache in milliseconds.
102 * If a persisted cache is found that is older than this
103 * time, it will be discarded
104 * @default 24 hours
105 */
106 maxAge?: number
107 /**
108 * Prefix to be used for storage key.
109 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
110 */
111 prefix?: string
112 /**
113 * Filters to narrow down which Queries should be persisted.
114 */
115 filters?: QueryFilters
117​
118interface AsyncStorage {
119 getItem: (key: string) => Promise<string | undefined | null>
120 setItem: (key: string, value: string) => Promise<unknown>
121 removeItem: (key: string) => Promise<void>
123```
124​
125The default options are:
126​
127```tsx
129 prefix = 'tanstack-query',
130 maxAge = 1000 * 60 * 60 * 24,
131 serialize = JSON.stringify,
132 deserialize = JSON.parse,
134```