Open History to see the last commit
1import { BroadcastChannel } from 'broadcast-channel'
2import type { BroadcastChannelOptions } from 'broadcast-channel'
3import type { QueryClient } from '@tanstack/query-core'
4β
5interface BroadcastQueryClientOptions {
6 queryClient: QueryClient
7 broadcastChannel?: string
8 options?: BroadcastChannelOptions
9}
10β
11export function broadcastQueryClient({
12 queryClient,
13 broadcastChannel = 'tanstack-query',
14 options,
15}: BroadcastQueryClientOptions) {
16 let transaction = false
17 const tx = (cb: () => void) => {
18 transaction = true
19 cb()
20 transaction = false
21 }
22β
23 const channel = new BroadcastChannel(broadcastChannel, {
24 webWorkerSupport: false,
25 ...options,
26 })
27β
28 const queryCache = queryClient.getQueryCache()
29β
30 queryClient.getQueryCache().subscribe((queryEvent) => {
31 if (transaction) {
32 return
33 }
34β
35 const {
36 query: { queryHash, queryKey, state },
37 } = queryEvent
38β
39 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
40 channel.postMessage({
41 type: 'updated',
42 queryHash,
43 queryKey,
44 state,
45 })
46 }
47β
48 if (queryEvent.type === 'removed') {
49 channel.postMessage({
50 type: 'removed',
51 queryHash,
52 queryKey,
53 })
54 }
55 })
56β
57 channel.onmessage = (action) => {
58 if (!action?.type) {
59 return
60 }
61β
62 tx(() => {
63 const { type, queryHash, queryKey, state } = action
64β
65 if (type === 'updated') {
66 const query = queryCache.get(queryHash)
67β
68 if (query) {
69 query.setState(state)
70 return
71 }
72β
73 queryCache.build(
74 queryClient,
75 {
76 queryKey,
77 queryHash,
78 },
79 state,
80 )
81 } else if (type === 'removed') {
82 const query = queryCache.get(queryHash)
83β
84 if (query) {
85 queryCache.remove(query)
86 }
87 }
88 })
89 }
90}