broadcastQueryClient(实验性)
极其重要:此工具目前处于实验阶段。这意味着破坏性变更可能出现在次要版本和补丁版本中。请自行承担使用风险。如果你选择在实验阶段于生产环境中依赖此工具,请将版本锁定到补丁级版本,以避免意外的中断。
broadcastQueryClient 是一个用于在同源的浏览器标签页/窗口之间广播并同步你的 queryClient 状态的工具。
安装
此工具作为一个独立包提供,可通过 '@tanstack/query-broadcast-client-experimental' 导入。
使用方法
导入 broadcastQueryClient 函数,传入你的 QueryClient 实例,并可选地设置一个 broadcastChannel。
TypeScript
1import { broadcastQueryClient } from '@tanstack/query-broadcast-client-experimental'2 3const queryClient = new QueryClient()4 5broadcastQueryClient({6 queryClient,7 broadcastChannel: 'my-app',8})API
broadcastQueryClient
向该函数传入一个 QueryClient 实例,并可选地传入一个 broadcastChannel。
TypeScript
1broadcastQueryClient({ queryClient, broadcastChannel })Options
一个选项对象:
TypeScript
1interface BroadcastQueryClientOptions {2 /** The QueryClient to sync */3 queryClient: QueryClient4 /** This is the unique channel name that will be used5 * to communicate between tabs and windows */6 broadcastChannel?: string7 /** Options for the BroadcastChannel API */8 options?: BroadcastChannelOptions9 /**10 * Called when a query event fails to broadcast to other tabs — most11 * commonly because the query's data, error, or key contains a value the12 * structured-clone algorithm cannot serialize (e.g. `ReadableStream`,13 * `File`, functions, Vue `reactive` proxies).14 *15 * If omitted, a `console.warn` is emitted in development so failures16 * are never entirely silent. May return a `Promise`; any rejection is17 * caught internally.18 */19 onBroadcastError?: (20 error: unknown,21 event: BroadcastErrorEvent,22 ) => void | Promise<void>23}24 25interface BroadcastErrorEvent {26 type: 'updated' | 'removed' | 'added'27 queryHash: string28 queryKey: QueryKey29}默认选项为:
TypeScript
1{2 broadcastChannel = 'tanstack-query',3}处理广播错误
如果你的缓存中包含非结构化可克隆(structured-cloneable)的值——例如 ReadableStream(来自 Response.body、流式 API 或 AI SDK)、File、函数,或 Vue reactive 等框架代理——底层的 BroadcastChannel.postMessage 调用将因该查询而被拒绝。该查询的跨标签页同步将被跳过;其余缓存仍会正常广播。
默认情况下,在开发环境中会触发一个 console.warn,确保失败不会静默发生。你可以提供 onBroadcastError,将失败路由至你自己的错误追踪器:
TypeScript
1import * as Sentry from '@sentry/browser'2import { broadcastQueryClient } from '@tanstack/query-broadcast-client-experimental'3 4broadcastQueryClient({5 queryClient,6 broadcastChannel: 'my-app',7 onBroadcastError: (error, event) => {8 Sentry.captureException(error, {9 tags: { broadcastEvent: event.type },10 extra: { queryHash: event.queryHash, queryKey: event.queryKey },11 })12 },13})