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): () => void {
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 const unsubscribe = queryClient.getQueryCache().subscribe((queryEvent) => {
31 if (transaction) {
32 return
33 }
34β
35 const {
36 query: { queryHash, queryKey, state, observers },
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' && observers.length > 0) {
49 channel.postMessage({
50 type: 'removed',
51 queryHash,
52 queryKey,
53 })
54 }
55β
56 if (queryEvent.type === 'added') {
57 channel.postMessage({
58 type: 'added',
59 queryHash,
60 queryKey,
61 })
62 }
63 })
64β
65 channel.onmessage = (action) => {
66 if (!action?.type) {
67 return
68 }
69β
70 tx(() => {
71 const { type, queryHash, queryKey, state } = action
72β
73 const query = queryCache.get(queryHash)
74β
75 if (type === 'updated') {
76 if (query) {
77 query.setState(state)
78 return
79 }
80β
81 queryCache.build(
82 queryClient,
83 {
84 queryKey,
85 queryHash,
86 },
87 state,
88 )
89 } else if (type === 'removed') {
90 if (query) {
91 queryCache.remove(query)
92 }
93 } else if (type === 'added') {
94 if (query) {
95 query.setState(state)
96 return
97 }
98 queryCache.build(
99 queryClient,
100 {
101 queryKey,
102 queryHash,
103 },
104 state,
105 )
106 }
107 })
108 }
109 return () => {
110 unsubscribe()
111 channel.close()
112 }
113}