Open History to see the last commit
1/**
2 * A Query Collection resubscribes its TanStack Query observers when its
3 * `subscriberCount` rises above zero, and a stale query refetches then. A live
4 * query that has no subscriber or preload of its own asks for no data, so it
5 * must not raise that count and must not cause a fetch. Its first subscriber
6 * does. The history first lets a direct subscriber leave, so the observers
7 * are unsubscribed and a resubscription would refetch.
8 */
9import { describe, expect, it } from 'vitest'
10import { QueryClient } from '@tanstack/query-core'
11import { createCollection, createLiveQueryCollection } from '@tanstack/db'
12import { queryCollectionOptions } from '../src/query'
13
14const settle = () => new Promise((resolve) => setTimeout(resolve, 20))
15
16describe(`a live query waiting for a subscriber`, () => {
17 it(`causes no Query Collection fetch until it has a subscriber`, async () => {
18 const queryClient = new QueryClient({
19 defaultOptions: { queries: { staleTime: 0, retry: false } },
20 })
21 let fetches = 0
22 const source = createCollection(
23 queryCollectionOptions({
24 id: `deferred-live-query-refetch`,
25 queryKey: [`deferred-live-query-refetch`],
26 queryClient,
27 getKey: (row: { id: string }) => row.id,
28 queryFn: () => {
29 fetches++
30 return Promise.resolve([{ id: `a` }])
31 },
32 startSync: true,
33 }),
34 )
35 const direct = source.subscribeChanges(() => {})
36 await settle()
37 direct.unsubscribe()
38 await settle()
39 const fetchesBefore = fetches
40
41 const live = createLiveQueryCollection({
42 query: (q) => q.from({ row: source }),
43 startSync: true,
44 })
45 try {
46 await settle()
47 expect(source.subscriberCount, `while the live query waits`).toBe(0)
48 expect(fetches, `no fetch while the live query waits`).toBe(fetchesBefore)
49
50 const subscription = live.subscribeChanges(() => {})
51 await settle()
52 expect(source.subscriberCount, `after its first subscriber`).toBe(1)
53 expect(fetches, `the subscriber resubscribes the stale query`).toBe(
54 fetchesBefore + 1,
55 )
56 subscription.unsubscribe()
57 } finally {
58 await live.cleanup()
59 await source.cleanup()
60 queryClient.clear()
61 }
62 })
63})