Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.ts

86 lines1.7 KB

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 }