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
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { QueryClient } from '@tanstack/query-core'
import { beforeEach, describe, expect, it } from 'vitest'
import { QueryClient, type QueryCache, type QueryState } from '@tanstack/query-core'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { broadcastQueryClient } from '..'
import type { QueryCache } from '@tanstack/query-core'

describe('broadcastQueryClient', () => {
let queryClient: QueryClient
let queryCache: QueryCache
const broadcastChannel = 'test_channel'

beforeEach(() => {
queryClient = new QueryClient()
Expand All @@ -15,17 +15,63 @@ describe('broadcastQueryClient', () => {
it('should subscribe to the query cache', () => {
broadcastQueryClient({
queryClient,
broadcastChannel: 'test_channel',
broadcastChannel,
})
expect(queryCache.hasListeners()).toBe(true)
})

it('should not have any listeners after cleanup', () => {
const unsubscribe = broadcastQueryClient({
queryClient,
broadcastChannel: 'test_channel',
broadcastChannel,
})
unsubscribe()
expect(queryCache.hasListeners()).toBe(false)
})

it('should sync initial query state when query is added from another tab', async () => {
const receiverClient = new QueryClient()
const senderClient = new QueryClient()

const senderUnsubscribe = broadcastQueryClient({
queryClient: senderClient,
broadcastChannel,
})
const receiverUnsubscribe = broadcastQueryClient({
queryClient: receiverClient,
broadcastChannel,
})

const seededData = { value: 'seeded' }
const seededState: QueryState<typeof seededData> = {
data: seededData,
dataUpdateCount: 1,
dataUpdatedAt: Date.now(),
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: 'success',
fetchStatus: 'idle',
}

senderClient.getQueryCache().build(
senderClient,
{ queryKey: ['seeded-query'] },
seededState,
)

const findState = () =>
receiverClient.getQueryCache().find({ queryKey: ['seeded-query'] })?.state

await vi.waitFor(() => {
expect(findState()).toMatchObject(seededState)
})

senderUnsubscribe()
receiverUnsubscribe()
})
})
4 changes: 4 additions & 0 deletions packages/query-broadcast-client-experimental/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function broadcastQueryClient({
type: 'added',
queryHash,
queryKey,
state,
})
}
})
Expand Down Expand Up @@ -92,6 +93,9 @@ export function broadcastQueryClient({
}
} else if (type === 'added') {
if (query) {
if (!state) {
return
}
query.setState(state)
return
}
Expand Down