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/broadcast-added-keeps-error.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 a query that has no data, such as one in error, when another tab broadcasts an `added` event for a query that has not settled yet
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,71 @@ describe('broadcastQueryClient', () => {
value: 'from other tab',
})
})

it('should not overwrite an existing query in error when an "added" message with a fresh state arrives for it', async () => {
const existingKey = queryKey()
const error = new Error('down')

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

await queryClient
.query({
queryKey: existingKey,
queryFn: () => Promise.reject(error),
retry: false,
})
.catch(() => undefined)
const existingQuery = queryCache.find({ queryKey: existingKey })!

lastCreatedChannel.onmessage?.({
type: 'added',
queryHash: existingQuery.queryHash,
queryKey: existingKey,
state: {
status: 'pending',
fetchStatus: 'idle',
data: undefined,
dataUpdatedAt: 0,
error: null,
errorUpdatedAt: 0,
},
})
expect(queryClient.getQueryState(existingKey)?.status).toBe('error')
expect(queryClient.getQueryState(existingKey)?.error).toBe(error)
})

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

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

const existingQuery = queryCache.build(queryClient, {
queryKey: existingKey,
})

lastCreatedChannel.onmessage?.({
type: 'added',
queryHash: existingQuery.queryHash,
queryKey: existingKey,
state: {
status: 'error',
fetchStatus: 'idle',
data: undefined,
dataUpdatedAt: 0,
error,
errorUpdatedAt: 0,
},
})
expect(queryClient.getQueryState(existingKey)?.status).toBe('error')
expect(queryClient.getQueryState(existingKey)?.error).toBe(error)
})
})

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