Open History to see the last commit
1---
2id: createAsyncStoragePersistor
3title: createAsyncStoragePersistor (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/createAsyncStoragePersistor-experimental` import.
11β
12## Usage
13β
14- Import the `createAsyncStoragePersistor` function
15- Create a new asyncStoragePersistor
16 - you can pass any `storage` to it that adheres to the `AsyncStorage` interface - the example below uses the async-storage from React Native
17- Pass it to the [`persistQueryClient`](./persistQueryClient) function
18β
19```ts
20import AsyncStorage from '@react-native-async-storage/async-storage'
21import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
22import { createAsyncStoragePersistor } from 'react-query/createAsyncStoragePersistor-experimental'
23β
24const queryClient = new QueryClient({
25 defaultOptions: {
26 queries: {
27 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
28 },
29 },
30})
31β
32const asyncStoragePersistor = createAsyncStoragePersistor({
33 storage: AsyncStorage
34})
35β
36persistQueryClient({
37 queryClient,
38 persistor: asyncStoragePersistor,
39})
40```
41β
42## API
43β
44### `createAsyncStoragePersistor`
45β
46Call this function to create an asyncStoragePersistor that you can use later with `persistQueryClient`.
47β
48```js
49createAsyncStoragePersistor(options: CreateAsyncStoragePersistorOptions)
50```
51β
52### `Options`
53β
54```ts
55interface CreateAsyncStoragePersistorOptions {
56 /** The storage client used for setting an retrieving items from cache */
57 storage: AsyncStorage
58 /** The key to use when storing the cache to localStorage */
59 key?: string
60 /** To avoid localStorage spamming,
61 * pass a time in ms to throttle saving the cache to disk */
62 throttleTime?: number
63 /** How to serialize the data to storage */
64 serialize?: (client: PersistedClient) => string
65 /** How to deserialize the data from storage */
66 deserialize?: (cachedString: string) => PersistedClient
67}
68β
69interface AsyncStorage {
70 getItem: (key: string) => Promise<string>
71 setItem: (key: string, value: string) => Promise<unknown>
72 removeItem: (key: string) => Promise<unknown>
73}
74```
75β
76The default options are:
77β
78```js
79{
80 key = `REACT_QUERY_OFFLINE_CACHE`,
81 throttleTime = 1000,
82 serialize = JSON.stringify,
83 deserialize = JSON.parse,
84}
85```