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

createPersister.md

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