Capítulo 49 de 80

Chapter 49: createAsyncStoragePersister

Core Idea

The recommended persister — accepts any storage adhering to the AsyncStorage interface (getItem/setItem/removeItem, all Promise-or-value returning), which includes both genuinely async storages (React Native's AsyncStorage) and synchronous ones like localStorage (a sync value satisfies a MaybePromise return type).

Key Concepts

  • Package: @tanstack/query-async-storage-persister (+ @tanstack/react-query-persist-client) — typically paired with PersistQueryClientProvider rather than the raw persistQueryClient function.
  • AsyncStorage interface: getItem/setItem/removeItem (each MaybePromise-returning) plus an optional entries() — broad enough that React Native's AsyncStorage, localStorage, and custom backends all qualify without adapters.
  • Retries: same mechanism and predefined strategies (e.g. removeOldestQuery) as the sync persister, just with an async-capable retry function type.
  • Options: identical shape to the sync persister — storage, key (default REACT_QUERY_OFFLINE_CACHE), throttleTime (default 1000ms), serialize/deserialize (default JSON), retry.

Code Examples

import AsyncStorage from '@react-native-async-storage/async-storage'

const asyncStoragePersister = createAsyncStoragePersister({ storage: AsyncStorage })

<PersistQueryClientProvider client={queryClient} persistOptions={{ persister: asyncStoragePersister }}>
  <App />
</PersistQueryClientProvider>
  • What it demonstrates: wiring React Native's AsyncStorage as the persistence backend via the recommended provider pattern.

Key Takeaways

  1. Default to this persister over createSyncStoragePersister for all new code — it's the maintained, non-deprecated option and works with sync storages too.
  2. Same gcTime/maxAge alignment requirement as any persister — see the persistQueryClient chapter.

Connects To

  • persistQueryClient: the gcTime/maxAge requirement and PersistQueryClientProvider this persister plugs into.
  • createSyncStoragePersister: the deprecated predecessor with the same options shape.