Skip to main content

createSyncStoragePersister

安装

这个工具作为一个独立的包提供,可以通过 @tanstack/query-sync-storage-persister 引入。


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

`pnpm add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client`

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

使用方法

导入 createSyncStoragePersister 函数 创建一个新的 syncStoragePersister 将其传递给 persistQueryClient 函数

import { persistQueryClient } from '@tanstack/react-query-persist-client';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';

const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 *60* 60 * 24, // 24小时
},
},
});

const localStoragePersister = createSyncStoragePersister({ storage: window.localStorage })
// const sessionStoragePersister = createSyncStoragePersister({ storage: window.sessionStorage })

persistQueryClient({
queryClient,
persister: localStoragePersister,
})

重试

持久化可能会失败,例如如果存储空间超过了可用空间。可以通过向 persister 提供重试函数来优雅地处理错误。

重试函数接收尝试保存的 PersistedClient、错误和错误计数作为输入。它应返回一个新的 PersistedClient,用于再次尝试持久化。如果返回 undefined,则不会进一步尝试持久化。

export type PersistRetryer = (props: {
persistedClient: PersistedClient,
error: Error,
errorCount: number,
}) => PersistedClient | undefined

预定义的策略

默认情况下,不会进行重试。您可以使用预定义的策略之一来处理重试。可以从 '@tanstack/react-query-persist-client' 导入它们:

removeOldestQuery:将返回一个新的 PersistedClient,其中移除了最旧的查询。

const localStoragePersister = createSyncStoragePersister({
storage: window.localStorage,
retry: removeOldestQuery,
});

API createSyncStoragePersister

调用此函数创建一个 syncStoragePersister,稍后可以与 persistQueryClient 一起使用。

createSyncStoragePersister(options: CreateSyncStoragePersisterOptions)

Options

interface CreateSyncStoragePersisterOptions {
/**用于从缓存设置和检索项目的存储客户端 (window.localStorage 或 window.sessionStorage) */
storage: Storage | undefined | null
/** 存储缓存时要使用的键*/
key?: string
/**为了避免过多频繁的保存缓存到磁盘,请传递一个以毫秒为单位的时间来进行节流 */
throttleTime?: number
/** 如何将数据序列化到存储中*/
serialize?: (client: PersistedClient) => string
/** 如何从存储中反序列化数据 */
deserialize?: (cachedString: string) => PersistedClient
/** 如何在错误时重试持久化 **/
retry?: PersistRetryer
}

默认选项为:

{
key = `REACT_QUERY_OFFLINE_CACHE`,
throttleTime = 1000,
serialize = JSON.stringify,
deserialize = JSON.parse,
}

serializedeserialize 选项

localStorage 可以存储的数据量是有限的。如果需要在 localStorage 中存储更多数据,可以覆盖 serialize 和 deserialize 函数,使用像 lz-string 这样的库来压缩和解压缩数据。

import { QueryClient } from '@tanstack/react-query';
import { persistQueryClient } from '@tanstack/react-query-persist-client';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';

import { compress, decompress } from 'lz-string';

const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });

persistQueryClient({
queryClient: queryClient,
persister: createSyncStoragePersister({
storage: window.localStorage,
serialize: data => compress(JSON.stringify(data)),
deserialize: data => JSON.parse(decompress(data)),
}),
maxAge: Infinity,
});

请注意,compress 和 decompress 函数是示例中使用的压缩和解压缩函数,具体的实现可能需要根据实际需求进行调整。