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

createAsyncStoragePersistor.md

85 lines2.5 KB

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
68​
69interface AsyncStorage {
70 getItem: (key: string) => Promise<string>
71 setItem: (key: string, value: string) => Promise<unknown>
72 removeItem: (key: string) => Promise<unknown>
74```
75​
76The default options are:
77​
78```js
80 key = `REACT_QUERY_OFFLINE_CACHE`,
81 throttleTime = 1000,
82 serialize = JSON.stringify,
83 deserialize = JSON.parse,
85```