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

createWebStoragePersister.md

128 lines3.9 KB

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