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

createSyncStoragePersister.md

149 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​
10```bash
11npm install @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
12```
13​
14or
15​
16```bash
17pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
18```
19​
20or
21​
22```bash
23yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client
24```
25​
26## Usage
27​
28- Import the `createSyncStoragePersister` function
29- Create a new syncStoragePersister
30- Pass it to the [`persistQueryClient`](../../plugins/persistQueryClient) function
31​
32```tsx
33import { persistQueryClient } from '@tanstack/react-query-persist-client'
34import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
35​
36const queryClient = new QueryClient({
37 defaultOptions: {
38 queries: {
39 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
40 },
41 },
42})
43​
44const localStoragePersister = createSyncStoragePersister({
45 storage: window.localStorage,
46})
47// const sessionStoragePersister = createSyncStoragePersister({ storage: window.sessionStorage })
48​
49persistQueryClient({
50 queryClient,
51 persister: localStoragePersister,
52})
53```
54​
55## Retries
56​
57Persistence 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.
58​
59The 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.
60​
61```tsx
62export type PersistRetryer = (props: {
63 persistedClient: PersistedClient
64 error: Error
65 errorCount: number
66}) => PersistedClient | undefined
67```
68​
69### Predefined strategies
70​
71Per 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'`:
72​
73- `removeOldestQuery`
74 - will return a new `PersistedClient` with the oldest query removed.
75​
76```tsx
77const localStoragePersister = createSyncStoragePersister({
78 storage: window.localStorage,
79 retry: removeOldestQuery,
80})
81```
82​
83## API
84​
85### `createSyncStoragePersister`
86​
87Call this function to create a syncStoragePersister that you can use later with `persistQueryClient`.
88​
89```tsx
90createSyncStoragePersister(options: CreateSyncStoragePersisterOptions)
91```
92​
93### `Options`
94​
95```tsx
96interface CreateSyncStoragePersisterOptions {
97 /** The storage client used for setting an retrieving items from cache (window.localStorage or window.sessionStorage) */
98 storage: Storage | undefined | null
99 /** The key to use when storing the cache */
100 key?: string
101 /** To avoid spamming,
102 * pass a time in ms to throttle saving the cache to disk */
103 throttleTime?: number
104 /** How to serialize the data to storage */
105 serialize?: (client: PersistedClient) => string
106 /** How to deserialize the data from storage */
107 deserialize?: (cachedString: string) => PersistedClient
108 /** How to retry persistence on error **/
109 retry?: PersistRetryer
111```
112​
113The default options are:
114​
115```tsx
117 key = `REACT_QUERY_OFFLINE_CACHE`,
118 throttleTime = 1000,
119 serialize = JSON.stringify,
120 deserialize = JSON.parse,
122```
123​
124#### `serialize` and `deserialize` options
125​
126There is a limit to the amount of data which can be stored in `localStorage`.
127If 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/).
128​
129```tsx
130import { QueryClient } from '@tanstack/react-query'
131import { persistQueryClient } from '@tanstack/react-query-persist-client'
132import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
133​
134import { compress, decompress } from 'lz-string'
135​
136const queryClient = new QueryClient({
137 defaultOptions: { queries: { staleTime: Infinity } },
138})
139​
140persistQueryClient({
141 queryClient: queryClient,
142 persister: createSyncStoragePersister({
143 storage: window.localStorage,
144 serialize: (data) => compress(JSON.stringify(data)),
145 deserialize: (data) => JSON.parse(decompress(data)),
146 }),
147 maxAge: Infinity,
148})
149```