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

createPersister.md

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