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

createAsyncStoragePersister.md

89 lines2.4 KB

1---
2id: createAsyncStoragePersister
3title: createAsyncStoragePersister
4---
5​
6## Installation
7​
8This utility comes packaged with `react-query` and is available under the `react-query/createAsyncStoragePersister` import.
9​
10## Usage
11​
12- Import the `createAsyncStoragePersister` function
13- Create a new asyncStoragePersister
14 - you can pass any `storage` to it that adheres to the `AsyncStorage` interface - the example below uses the async-storage from React Native
15- Pass it to the [`persistQueryClient`](./persistQueryClient) function
16​
17```ts
18import AsyncStorage from '@react-native-async-storage/async-storage'
19import { persistQueryClient } from 'react-query/persistQueryClient'
20import { createAsyncStoragePersister } from 'react-query/createAsyncStoragePersister'
21​
22const queryClient = new QueryClient({
23 defaultOptions: {
24 queries: {
25 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
26 },
27 },
28})
29​
30const asyncStoragePersister = createAsyncStoragePersister({
31 storage: AsyncStorage
32})
33​
34persistQueryClient({
35 queryClient,
36 persister: asyncStoragePersister,
37})
38```
39​
40## Retries
41​
42Retries work the same as for a [WebStoragePersister](./createWebStoragePersister), except that they can also be asynchronous. You can also use all the predefined retry handlers.
43​
44## API
45​
46### `createAsyncStoragePersister`
47​
48Call this function to create an asyncStoragePersister that you can use later with `persistQueryClient`.
49​
50```js
51createAsyncStoragePersister(options: CreateAsyncStoragePersisterOptions)
52```
53​
54### `Options`
55​
56```ts
57interface CreateAsyncStoragePersisterOptions {
58 /** The storage client used for setting an retrieving items from cache */
59 storage: AsyncStorage
60 /** The key to use when storing the cache to localStorage */
61 key?: string
62 /** To avoid localStorage spamming,
63 * pass a time in ms to throttle saving the cache to disk */
64 throttleTime?: number
65 /** How to serialize the data to storage */
66 serialize?: (client: PersistedClient) => string
67 /** How to deserialize the data from storage */
68 deserialize?: (cachedString: string) => PersistedClient
69 /** How to retry persistence on error **/
70 retry?: AsyncPersistRetryer
72​
73interface AsyncStorage {
74 getItem: (key: string) => Promise<string>
75 setItem: (key: string, value: string) => Promise<unknown>
76 removeItem: (key: string) => Promise<unknown>
78```
79​
80The default options are:
81​
82```js
84 key = `REACT_QUERY_OFFLINE_CACHE`,
85 throttleTime = 1000,
86 serialize = JSON.stringify,
87 deserialize = JSON.parse,
89```