createAsyncStoragePersister

· abundance's blog


Installation #

This utility comes as a separate package and is available under the '@tanstack/query-async-storage-persister' import.

1npm install @tanstack/query-async-storage-persister @tanstack/react-query-persist-client

or

1pnpm add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client

or

1yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client

or

1bun add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client

Usage #

 1import AsyncStorage from '@react-native-async-storage/async-storage'
 2import { QueryClient } from '@tanstack/react-query'
 3import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
 4import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
 5
 6const queryClient = new QueryClient({
 7  defaultOptions: {
 8    queries: {
 9      gcTime: 1000 * 60 * 60 * 24, // 24 hours
10    },
11  },
12})
13
14const asyncStoragePersister = createAsyncStoragePersister({
15  storage: AsyncStorage,
16})
17
18const Root = () => (
19  <PersistQueryClientProvider
20    client={queryClient}
21    persistOptions={{ persister: asyncStoragePersister }}
22  >
23    <App />
24  </PersistQueryClientProvider>
25)
26
27export default Root

Retries #

Retries work the same as for a SyncStoragePersister, except that they can also be asynchronous. You can also use all the predefined retry handlers.

API #

createAsyncStoragePersister #

Call this function to create an asyncStoragePersister that you can use later with persistQueryClient.

1createAsyncStoragePersister(options: CreateAsyncStoragePersisterOptions)

Options #

 1interface CreateAsyncStoragePersisterOptions {
 2  /** The storage client used for setting an retrieving items from cache */
 3  storage: AsyncStorage | undefined | null
 4  /** The key to use when storing the cache to localStorage */
 5  key?: string
 6  /** To avoid localStorage spamming,
 7   * pass a time in ms to throttle saving the cache to disk */
 8  throttleTime?: number
 9  /** How to serialize the data to storage */
10  serialize?: (client: PersistedClient) => string
11  /** How to deserialize the data from storage */
12  deserialize?: (cachedString: string) => PersistedClient
13  /** How to retry persistence on error **/
14  retry?: AsyncPersistRetryer
15}
16
17interface AsyncStorage {
18  getItem: (key: string) => Promise<string | null>
19  setItem: (key: string, value: string) => Promise<unknown>
20  removeItem: (key: string) => Promise<void>
21}

The default options are:

1{
2  key = `REACT_QUERY_OFFLINE_CACHE`,
3  throttleTime = 1000,
4  serialize = JSON.stringify,
5  deserialize = JSON.parse,
6}