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