Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-broadcast-added-overwrites-existing-data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-broadcast-client-experimental': patch
---

fix: don't overwrite an existing query's resolved data when another tab broadcasts an `added` event for it
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,63 @@ describe('broadcastQueryClient', () => {

expect(mockPostMessage).toHaveBeenCalled()
})

it('should not overwrite an existing query with data when an "added" message arrives for it', () => {
const existingKey = queryKey()

broadcastQueryClient({
queryClient,
broadcastChannel: 'test_channel',
})

// A query that already resolved in this tab (e.g. it fetched before
// another tab mounted the same key).
queryClient.setQueryData(existingKey, { value: 'resolved' })
const existingQuery = queryCache.find({ queryKey: existingKey })!

// Another tab just mounted the same key for the first time, so its
// `build()` broadcasts an `added` message with a pending state and
// no data.
lastCreatedChannel.onmessage?.({
type: 'added',
queryHash: existingQuery.queryHash,
queryKey: existingKey,
state: { status: 'pending', data: undefined },
})

expect(queryClient.getQueryData(existingKey)).toEqual({
value: 'resolved',
})
expect(queryClient.getQueryState(existingKey)?.status).toBe('success')
})

it('should adopt an "added" message\'s state for an existing query that has no data yet', () => {
const existingKey = queryKey()

broadcastQueryClient({
queryClient,
broadcastChannel: 'test_channel',
})

// This tab has already built the query (e.g. an observer mounted it)
// but hasn't fetched it yet.
const existingQuery = queryCache.build(queryClient, {
queryKey: existingKey,
})

// Another tab already had this key resolved (e.g. via `initialData`)
// when it mounted, so its `added` message carries real data.
lastCreatedChannel.onmessage?.({
type: 'added',
queryHash: existingQuery.queryHash,
queryKey: existingKey,
state: { status: 'success', data: { value: 'from other tab' } },
})

expect(queryClient.getQueryData(existingKey)).toEqual({
value: 'from other tab',
})
})
})

describe('postMessage error handling', () => {
Expand Down
4 changes: 3 additions & 1 deletion packages/query-broadcast-client-experimental/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,9 @@ export function broadcastQueryClient({
}
} else if (type === 'added') {
if (query) {
query.setState(state)
if (query.state.data === undefined) {
query.setState(state)
}
return
}
queryCache.build(
Expand Down