译零 TransZero · TanStack Query v3 中文文档
主站

createAsyncStoragePersistor (Experimental)

VERY IMPORTANT: This utility is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages.

Installation

This utility comes packaged with react-query and is available under the react-query/createAsyncStoragePersistor-experimental import.

Usage

  • Import the createAsyncStoragePersistor function
  • Create a new asyncStoragePersistor
    • you can pass any storage to it that adheres to the AsyncStorage interface - the example below uses the async-storage from React Native
  • Pass it to the persistQueryClient function
TypeScript
1import AsyncStorage from "@react-native-async-storage/async-storage";2import { persistQueryClient } from "react-query/persistQueryClient-experimental";3import { createAsyncStoragePersistor } from "react-query/createAsyncStoragePersistor-experimental";4 5const queryClient = new QueryClient({6  defaultOptions: {7    queries: {8      cacheTime: 1000 * 60 * 60 * 24, // 24 hours9    },10  },11});12 13const asyncStoragePersistor = createAsyncStoragePersistor({14  storage: AsyncStorage,15});16 17persistQueryClient({18  queryClient,19  persistor: asyncStoragePersistor,20});

API

createAsyncStoragePersistor

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

JavaScript
1createAsyncStoragePersistor(options: CreateAsyncStoragePersistorOptions)

Options

TypeScript
1interface CreateAsyncStoragePersistorOptions {2  /** The storage client used for setting an retrieving items from cache */3  storage: AsyncStorage;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}14 15interface AsyncStorage {16  getItem: (key: string) => Promise<string>;17  setItem: (key: string, value: string) => Promise<unknown>;18  removeItem: (key: string) => Promise<unknown>;19}

The default options are:

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

本页为 TanStack Query 文档(React 版)的非官方中文翻译,原文由上游团队维护,遵循 MIT 许可。 译文如有偏差,以英文原文为准。

本页译文取自社区中文版 react-query-web-i18n(MIT),非本站翻译,已停止更新,内容可能与当前 API 有出入。

译自上游 (未记录版本)