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

index.ts

90 lines1.9 KB

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 }