createAsyncStoragePersister
Installation
This utility comes as a separate package and is available under the '@tanstack/query-async-storage-persister' import.
Shell
1npm install @tanstack/query-async-storage-persister @tanstack/react-query-persist-clientor
Shell
1pnpm add @tanstack/query-async-storage-persister @tanstack/react-query-persist-clientor
Shell
1yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-clientUsage
- Import the
createAsyncStoragePersisterfunction - Create a new asyncStoragePersister
- you can pass any
storageto it that adheres to theAsyncStorageinterface - the example below uses the async-storage from React Native
- you can pass any
- Wrap your app by using
PersistQueryClientProvidercomponent.
TypeScript
1import AsyncStorage from "@react-native-async-storage/async-storage";2import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";3import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";4 5const queryClient = new QueryClient({6 defaultOptions: {7 queries: {8 cacheTime: 1000 * 60 * 60 * 24, // 24 hours9 },10 },11});12 13const asyncStoragePersister = createAsyncStoragePersister({14 storage: AsyncStorage,15});16 17const Root = () => (18 <PersistQueryClientProvider19 client={queryClient}20 persistOptions={{ persister: asyncStoragePersister }}21 >22 <App />23 </PersistQueryClientProvider>24);25 26export 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.
TypeScript
1createAsyncStoragePersister(options: CreateAsyncStoragePersisterOptions)Options
TypeScript
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:
TypeScript
1{2 key = `REACT_QUERY_OFFLINE_CACHE`,3 throttleTime = 1000,4 serialize = JSON.stringify,5 deserialize = JSON.parse,6}