框架
版本

experimental_createPersister

安装

此实用程序作为一个单独的包提供,可通过 '@tanstack/query-persist-client-core' 导入使用。

bash
npm install @tanstack/query-persist-client-core
npm install @tanstack/query-persist-client-core

bash
pnpm add @tanstack/query-persist-client-core
pnpm add @tanstack/query-persist-client-core

bash
yarn add @tanstack/query-persist-client-core
yarn add @tanstack/query-persist-client-core

bash
bun add @tanstack/query-persist-client-core
bun add @tanstack/query-persist-client-core

注意:此实用程序也包含在 @tanstack/react-query-persist-client 包中,如果您正在使用该包,则无需单独安装。

用法

  • 导入 experimental_createPersister 函数
  • 创建一个新的 experimental_createPersister
    • 您可以向其传递任何符合 AsyncStorageStorage 接口的 storage - 下面的示例使用了 React Native 的 async-storage。
  • 将该 persister 作为选项传递给您的 Query。这可以通过将其传递给 QueryClientdefaultOptions 或任何 useQuery hook 实例来完成。
    • 如果您将此 persister 作为 defaultOptions 传递,则所有查询都将持久化到提供的 storage 中。您还可以通过传递 filters 来缩小范围。与 persistClient 插件相比,这不会将整个查询客户端作为单个项目持久化,而是单独持久化每个查询。查询哈希用作键。
    • 如果您将此 persister 提供给单个 useQuery hook,则只有此 Query 将被持久化。

这样,您无需存储整个 QueryClient,而是选择在您的应用程序中值得持久化的内容。每个查询都会被懒加载恢复(当首次使用 Query 时)并在每次 queryFn 运行后持久化,因此无需进行节流。在恢复 Query 后,staleTime 也会被遵守,因此如果数据被认为是过时的,则会在恢复后立即重新获取。如果数据是新的,则 queryFn 不会运行。

从内存中垃圾回收 Query 不会影响持久化数据。这意味着可以将 Query 在内存中保留较短的时间以提高 内存效率。如果下次使用它们,它们将再次从持久存储中恢复。

tsx
import AsyncStorage from '@react-native-async-storage/async-storage'
import { QueryClient } from '@tanstack/react-query'
import { experimental_createPersister } from '@tanstack/query-persist-client-core'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      gcTime: 1000 * 30, // 30 seconds
      persister: experimental_createPersister({
        storage: AsyncStorage,
        maxAge: 1000 * 60 * 60 * 12, // 12 hours
      }),
    },
  },
})
import AsyncStorage from '@react-native-async-storage/async-storage'
import { QueryClient } from '@tanstack/react-query'
import { experimental_createPersister } from '@tanstack/query-persist-client-core'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      gcTime: 1000 * 30, // 30 seconds
      persister: experimental_createPersister({
        storage: AsyncStorage,
        maxAge: 1000 * 60 * 60 * 12, // 12 hours
      }),
    },
  },
})

调整后的默认值

createPersister 插件在技术上包装了 queryFn,因此如果 queryFn 没有运行,它就不会恢复。这样,它充当 Query 和网络之间的缓存层。因此,当使用 persister 时,networkMode 默认为 'offlineFirst',以便即使没有网络连接,也可以从持久存储中恢复。

API

experimental_createPersister

tsx
experimental_createPersister(options: StoragePersisterOptions)
experimental_createPersister(options: StoragePersisterOptions)

选项

tsx
export interface StoragePersisterOptions {
  /** The storage client used for setting and retrieving items from cache.
   * For SSR pass in `undefined`.
   */
  storage: AsyncStorage | Storage | undefined | null
  /**
   * How to serialize the data to storage.
   * @default `JSON.stringify`
   */
  serialize?: (persistedQuery: PersistedQuery) => string
  /**
   * How to deserialize the data from storage.
   * @default `JSON.parse`
   */
  deserialize?: (cachedString: string) => PersistedQuery
  /**
   * A unique string that can be used to forcefully invalidate existing caches,
   * if they do not share the same buster string
   */
  buster?: string
  /**
   * The max-allowed age of the cache in milliseconds.
   * If a persisted cache is found that is older than this
   * time, it will be discarded
   * @default 24 hours
   */
  maxAge?: number
  /**
   * Prefix to be used for storage key.
   * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
   */
  prefix?: string
  /**
   * Filters to narrow down which Queries should be persisted.
   */
  filters?: QueryFilters
}

interface AsyncStorage {
  getItem: (key: string) => Promise<string | undefined | null>
  setItem: (key: string, value: string) => Promise<unknown>
  removeItem: (key: string) => Promise<void>
}
export interface StoragePersisterOptions {
  /** The storage client used for setting and retrieving items from cache.
   * For SSR pass in `undefined`.
   */
  storage: AsyncStorage | Storage | undefined | null
  /**
   * How to serialize the data to storage.
   * @default `JSON.stringify`
   */
  serialize?: (persistedQuery: PersistedQuery) => string
  /**
   * How to deserialize the data from storage.
   * @default `JSON.parse`
   */
  deserialize?: (cachedString: string) => PersistedQuery
  /**
   * A unique string that can be used to forcefully invalidate existing caches,
   * if they do not share the same buster string
   */
  buster?: string
  /**
   * The max-allowed age of the cache in milliseconds.
   * If a persisted cache is found that is older than this
   * time, it will be discarded
   * @default 24 hours
   */
  maxAge?: number
  /**
   * Prefix to be used for storage key.
   * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
   */
  prefix?: string
  /**
   * Filters to narrow down which Queries should be persisted.
   */
  filters?: QueryFilters
}

interface AsyncStorage {
  getItem: (key: string) => Promise<string | undefined | null>
  setItem: (key: string, value: string) => Promise<unknown>
  removeItem: (key: string) => Promise<void>
}

默认选项是

tsx
{
  prefix = 'tanstack-query',
  maxAge = 1000 * 60 * 60 * 24,
  serialize = JSON.stringify,
  deserialize = JSON.parse,
}
{
  prefix = 'tanstack-query',
  maxAge = 1000 * 60 * 60 * 24,
  serialize = JSON.stringify,
  deserialize = JSON.parse,
}