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