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

index.ts

89 lines1.8 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 || !queryEvent?.query) {
28 return
29 }
30​
31 const {
32 query: { queryHash, queryKey, state },
33 } = queryEvent
34​
35 if (
36 queryEvent.type === 'queryUpdated' &&
37 queryEvent.action?.type === 'success'
38 ) {
39 channel.postMessage({
40 type: 'queryUpdated',
41 queryHash,
42 queryKey,
43 state,
44 })
45 }
46​
47 if (queryEvent.type === 'queryRemoved') {
48 channel.postMessage({
49 type: 'queryRemoved',
50 queryHash,
51 queryKey,
52 })
53 }
54 })
55​
56 channel.onmessage = action => {
57 if (!action?.type) {
58 return
59 }
60​
61 tx(() => {
62 const { type, queryHash, queryKey, state } = action
63​
64 if (type === 'queryUpdated') {
65 const query = queryCache.get(queryHash)
66​
67 if (query) {
68 query.setState(state)
69 return
70 }
71​
72 queryCache.build(
73 queryClient,
74 {
75 queryKey,
76 queryHash,
77 },
78 state
79 )
80 } else if (type === 'queryRemoved') {
81 const query = queryCache.get(queryHash)
82​
83 if (query) {
84 queryCache.remove(query)
85 }
86 }
87 })
88 }