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

createSyncStoragePersister.md

139 lines4.3 KB

1---
2id: createSyncStoragePersister
3title: createSyncStoragePersister
4---
5​
6## Installation
7​
8This utility comes as a separate package and is available under the `'@tanstack/query-sync-storage-persister'` import.
9```bash
10npm install @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
11```
12or
13```bash
14pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
15```
16or
17```bash
18yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
19```
20​
21## Usage
22​
23- Import the `createSyncStoragePersister` function
24- Create a new syncStoragePersister
25- Pass it to the [`persistQueryClient`](../plugins/persistQueryClient) function
26​
27```tsx
28import { persistQueryClient } from '@tanstack/react-query-persist-client'
29import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
30​
31const queryClient = new QueryClient({
32 defaultOptions: {
33 queries: {
34 gcTime: 1000 * 60 * 60 * 24, // 24 hours
35 },
36 },
37})
38​
39const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage })
40// const sessionStoragePersister = createSyncStoragePersister({ storage: window.sessionStorage })
41​
42persistQueryClient({
43 queryClient,
44 persister: localStoragePersister,
45})
46```
47​
48## Retries
49​
50Persistence can fail, e.g. if the size exceeds the available space on the storage. Errors can be handled gracefully by providing a `retry` function to the persister.
51​
52The retry function receives the `persistedClient` it tried to save, as well as the `error` and the `errorCount` as input. It is expected to return a _new_ `PersistedClient`, with which it tries to persist again. If _undefined_ is returned, there will be no further attempt to persist.
53​
54```tsx
55export type PersistRetryer = (props: {
56 persistedClient: PersistedClient
57 error: Error
58 errorCount: number
59}) => PersistedClient | undefined
60```
61​
62### Predefined strategies
63​
64Per default, no retry will occur. You can use one of the predefined strategies to handle retries. They can be imported `from '@tanstack/react-query-persist-client'`:
65​
66- `removeOldestQuery`
67 - will return a new `PersistedClient` with the oldest query removed.
68​
69```tsx
70const localStoragePersister = createSyncStoragePersister({
71 storage: window.localStorage,
72 retry: removeOldestQuery
73})
74```
75​
76## API
77​
78### `createSyncStoragePersister`
79​
80Call this function to create a syncStoragePersister that you can use later with `persistQueryClient`.
81​
82```tsx
83createSyncStoragePersister(options: CreateSyncStoragePersisterOptions)
84```
85​
86### `Options`
87​
88```tsx
89interface CreateSyncStoragePersisterOptions {
90 /** The storage client used for setting an retrieving items from cache (window.localStorage or window.sessionStorage) */
91 storage: Storage | undefined | null
92 /** The key to use when storing the cache */
93 key?: string
94 /** To avoid spamming,
95 * pass a time in ms to throttle saving the cache to disk */
96 throttleTime?: number
97 /** How to serialize the data to storage */
98 serialize?: (client: PersistedClient) => string
99 /** How to deserialize the data from storage */
100 deserialize?: (cachedString: string) => PersistedClient
101 /** How to retry persistence on error **/
102 retry?: PersistRetryer
104```
105​
106The default options are:
107​
108```tsx
110 key = `REACT_QUERY_OFFLINE_CACHE`,
111 throttleTime = 1000,
112 serialize = JSON.stringify,
113 deserialize = JSON.parse,
115```
116​
117#### `serialize` and `deserialize` options
118There is a limit to the amount of data which can be stored in `localStorage`.
119If you need to store more data in `localStorage`, you can override the `serialize` and `deserialize` functions to compress and decrompress the data using a library like [lz-string](https://github.com/pieroxy/lz-string/).
120​
121```tsx
122import { QueryClient } from '@tanstack/react-query';
123import { persistQueryClient } from '@tanstack/react-query-persist-client'
124import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
125​
126import { compress, decompress } from 'lz-string';
127​
128const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
129​
130persistQueryClient({
131 queryClient: queryClient,
132 persister: createSyncStoragePersister({
133 storage: window.localStorage,
134 serialize: data => compress(JSON.stringify(data)),
135 deserialize: data => JSON.parse(decompress(data)),
136 }),
137 maxAge: Infinity,
138});
139```