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

createWebStoragePersistor.md

76 lines2.2 KB

1---
2id: createWebStoragePersistor
3title: createWebStoragePersistor (Experimental)
4---
5​
6> VERY IMPORTANT: This utility is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages.
7​
8## Installation
9​
10This utility comes packaged with `react-query` and is available under the `react-query/createWebStoragePersistor-experimental` import.
11​
12## Usage
13​
14- Import the `createWebStoragePersistor` function
15- Create a new webStoragePersistor
16- Pass it to the [`persistQueryClient`](./persistQueryClient) function
17​
18```ts
19import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
20import { createWebStoragePersistor } from 'react-query/createWebStoragePersistor-experimental'
21​
22const queryClient = new QueryClient({
23 defaultOptions: {
24 queries: {
25 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
26 },
27 },
28})
29​
30const localStoragePersistor = createWebStoragePersistor({ storage: window.localStorage })
31// const sessionStoragePersistor = createWebStoragePersistor({ storage: window.sessionStorage })
32​
33persistQueryClient({
34 queryClient,
35 persistor: localStoragePersistor,
36})
37```
38​
39## API
40​
41### `createWebStoragePersistor`
42​
43Call this function to create a webStoragePersistor that you can use later with `persistQueryClient`.
44​
45```js
46createWebStoragePersistor(options: CreateWebStoragePersistorOptions)
47```
48​
49### `Options`
50​
51```ts
52interface CreateWebStoragePersistorOptions {
53 /** The storage client used for setting an retrieving items from cache (window.localStorage or window.sessionStorage) */
54 storage: Storage
55 /** The key to use when storing the cache */
56 key?: string
57 /** To avoid spamming,
58 * pass a time in ms to throttle saving the cache to disk */
59 throttleTime?: number
60 /** How to serialize the data to storage */
61 serialize?: (client: PersistedClient) => string
62 /** How to deserialize the data from storage */
63 deserialize?: (cachedString: string) => PersistedClient
65```
66​
67The default options are:
68​
69```js
71 key = `REACT_QUERY_OFFLINE_CACHE`,
72 throttleTime = 1000,
73 serialize = JSON.stringify,
74 deserialize = JSON.parse,
76```