Open History to see the last commit
1import { BroadcastChannel } from 'broadcast-channel'
2import type { BroadcastChannelOptions } from 'broadcast-channel'
3import type { QueryClient, QueryKey } from '@tanstack/query-core'
4β
5/**
6 * Metadata describing a broadcast that failed to be delivered to other tabs.
7 * Passed to {@link BroadcastQueryClientOptions.onBroadcastError} so callers
8 * can correlate failures with the originating query.
9 */
10export interface BroadcastErrorEvent {
11 type: 'updated' | 'removed' | 'added'
12 queryHash: string
13 queryKey: QueryKey
14}
15β
16type BroadcastMessage =
17 | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown }
18 | { type: 'removed'; queryHash: string; queryKey: QueryKey }
19 | { type: 'added'; queryHash: string; queryKey: QueryKey; state: unknown }
20β
21interface BroadcastQueryClientOptions {
22 /** The QueryClient to sync. */
23 queryClient: QueryClient
24 /**
25 * Unique channel name used to communicate between tabs and windows.
26 * @default 'tanstack-query'
27 */
28 broadcastChannel?: string
29 /** Options forwarded to the underlying `BroadcastChannel`. */
30 options?: BroadcastChannelOptions
31 /**
32 * Called when a query event fails to broadcast to other tabs β most
33 * commonly because the query's `state.data`, `state.error`, or `queryKey`
34 * contains a value the structured-clone algorithm cannot serialize
35 * (e.g. `ReadableStream`, `File`, functions, Vue `reactive` proxies).
36 *
37 * Provide this to route failures to an error tracker. If omitted, a
38 * `console.warn` is emitted in development so failures are never silent.
39 *
40 * May return a `Promise`; any rejection is caught internally so it cannot
41 * cause a secondary unhandled rejection.
42 */
43 onBroadcastError?: (
44 error: unknown,
45 event: BroadcastErrorEvent,
46 ) => void | Promise<void>
47}
48β
49export function broadcastQueryClient({
50 queryClient,
51 broadcastChannel = 'tanstack-query',
52 options,
53 onBroadcastError,
54}: BroadcastQueryClientOptions): () => void {
55 let transaction = false
56 const tx = (cb: () => void) => {
57 transaction = true
58 cb()
59 transaction = false
60 }
61β
62 const channel = new BroadcastChannel(broadcastChannel, {
63 webWorkerSupport: false,
64 ...options,
65 })
66β
67 const queryCache = queryClient.getQueryCache()
68β
69 const safePost = (message: BroadcastMessage): void => {
70 channel.postMessage(message).catch((error: unknown) => {
71 const event: BroadcastErrorEvent = {
72 type: message.type,
73 queryHash: message.queryHash,
74 queryKey: message.queryKey,
75 }
76β
77 if (onBroadcastError) {
78 const warnCallbackError = (callbackError: unknown) => {
79 if (process.env.NODE_ENV !== 'production') {
80 console.warn(
81 `[broadcastQueryClient] onBroadcastError threw while handling "${event.type}" for query ${event.queryHash}.`,
82 callbackError,
83 )
84 }
85 }
86 let result: void | Promise<void>
87 try {
88 result = onBroadcastError(error, event)
89 } catch (callbackError) {
90 warnCallbackError(callbackError)
91 return
92 }
93 result?.catch(warnCallbackError)
94 } else if (process.env.NODE_ENV !== 'production') {
95 console.warn(
96 `[broadcastQueryClient] Failed to broadcast "${event.type}" event for query ${event.queryHash}. ` +
97 'The query value could not be structured-cloned; cross-tab sync for this query was skipped.',
98 error,
99 )
100 }
101 })
102 }
103β
104 const unsubscribe = queryCache.subscribe((queryEvent) => {
105 if (transaction) {
106 return
107 }
108β
109 const {
110 query: { queryHash, queryKey, state, observers },
111 } = queryEvent
112β
113 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
114 safePost({
115 type: 'updated',
116 queryHash,
117 queryKey,
118 state,
119 })
120 }
121β
122 if (queryEvent.type === 'removed' && observers.length > 0) {
123 safePost({
124 type: 'removed',
125 queryHash,
126 queryKey,
127 })
128 }
129β
130 if (queryEvent.type === 'added') {
131 safePost({
132 type: 'added',
133 queryHash,
134 queryKey,
135 state,
136 })
137 }
138 })
139β
140 channel.onmessage = (action) => {
141 if (!action?.type) {
142 return
143 }
144β
145 tx(() => {
146 const { type, queryHash, queryKey, state } = action
147β
148 const query = queryCache.get(queryHash)
149β
150 if (type === 'updated') {
151 if (query) {
152 query.setState(state)
153 return
154 }
155β
156 queryCache.build(
157 queryClient,
158 {
159 queryKey,
160 queryHash,
161 },
162 state,
163 )
164 } else if (type === 'removed') {
165 if (query) {
166 queryCache.remove(query)
167 }
168 } else if (type === 'added') {
169 if (query) {
170 query.setState(state)
171 return
172 }
173 queryCache.build(
174 queryClient,
175 {
176 queryKey,
177 queryHash,
178 },
179 state,
180 )
181 }
182 })
183 }
184 return () => {
185 unsubscribe()
186 channel.close()
187 }
188}