T
TanStack10mo ago
firm-tan

Best way to sync queries across tabs?

Right now, I am using BroadcastChannel API in a Provider using Context which listens to messages and also provides a send message function I use to broadcast changes. Just wondering if there is a clear/better way for this? It has become somewhat of a maintenance nightmare to keep up. AFAIK there is no official Tanstack Query support for this? please correct me if I am wrong. Would be great to implement something that directly injects into Query Client that automatically broadcasts/listens to invalidate query calls. Thanks in advance.
3 Replies
passive-yellow
passive-yellow10mo ago
I don't know that I'd have much hope of RQ implementing something internally, but your BroadcastChannel idea sounds good. I do something similar to ensure authentication across all tabs stays in sync (ie, one tab logs out they all log out). Something along the lines of this?
const channel = new BroadcastChannel('react-query')

const queryClient = new QueryClient({
mutationCache: new MutationCache({
onSuccess: (data, variables, context, mutation) => {
channel.postMessage({
data,
variables,
context,
mutation
})
},
})
})
const channel = new BroadcastChannel('react-query')

const queryClient = new QueryClient({
mutationCache: new MutationCache({
onSuccess: (data, variables, context, mutation) => {
channel.postMessage({
data,
variables,
context,
mutation
})
},
})
})
Then the other tabs can have channel.addEventListener('message', ...) to perform query invalidations for themselves. That mutation.meta could include the queryKey(s) you wish to invalidate, for example
extended-salmon
extended-salmon10mo ago
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
From An unknown user
From An unknown user
passive-yellow
passive-yellow10mo ago
Oof

Did you find this page helpful?