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

createSyncStoragePersister.md

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