Open History to see the last commit
1/**
2 * React receiving driver for the core Effect metadata owner's callback law.
3 * The shared oracle authors source versions, callback changes and comparisons.
4 * Real renderHook/act commits supply the hook's callback-replacement premise.
5 * Observation cuts follow act and one host turn. This covers eager sources,
6 * not arbitrary host scheduling or other framework bindings.
7 */
8import { afterAll, test } from 'vitest'
9import { act, renderHook } from '@testing-library/react'
10import { Query, createCollection } from '@tanstack/db'
11import { useLiveQueryEffect } from '../src/useLiveQueryEffect'
12import {
13 callbackHistories,
14 callbackReach,
15 runCallbackHistory,
16} from '../../db/tests/query/effect-callback-oracle'
17import { checkWithCleanup } from '../../db/tests/query/virtual-row-fields-support'
18import { flushPromises, mockSyncCollectionOptions } from '../../db/tests/utils'
19import type {
20 CallbackOutput,
21 CallbackRow,
22} from '../../db/tests/query/effect-callback-oracle'
23import type { EffectConfig } from '@tanstack/db'
24
25const reach = callbackReach(`React`)
26let ran = false
27afterAll(() => {
28 if (ran) reach.assertReached()
29 if (process.env.TANSTACK_DB_ORACLE_STATISTICS === `1`)
30 console.info(
31 `Effect React callback reach`,
32 Object.fromEntries(reach.counts()),
33 )
34})
35test.each(callbackHistories)(
36 `receives current Effect values across callback profiles: %j`,
37 async (history) => {
38 ran = true
39 await runCallbackHistory(
40 history,
41 {
42 mount: async ({ skipInitial, project, handlers }) => {
43 const source = createCollection(
44 mockSyncCollectionOptions<CallbackRow>({
45 id: `callback-react`,
46 getKey: (row) => row.id,
47 initialData: [{ id: 1, version: 0 }],
48 }),
49 )
50 await source.preload()
51 const query = new Query()
52 .from({ row: source })
53 .fn.select(({ row }) => project(row))
54 const mounted = renderHook(
55 ({ config }: { config: EffectConfig<CallbackOutput> }) =>
56 useLiveQueryEffect(config),
57 { initialProps: { config: { query, skipInitial, ...handlers } } },
58 )
59 await act(async () => {
60 await flushPromises()
61 })
62 return {
63 write: async (type, version) => {
64 await act(async () => {
65 source.utils.begin()
66 source.utils.write({ type, value: { id: 1, version } })
67 source.utils.commit()
68 await flushPromises()
69 })
70 },
71 replaceHandlers: async (replacement) => {
72 mounted.rerender({
73 config: { query, skipInitial, ...replacement },
74 })
75 await act(async () => {
76 await flushPromises()
77 })
78 },
79 dispose: async () => {
80 mounted.unmount()
81 await act(async () => {
82 await flushPromises()
83 })
84 },
85 cleanup: () =>
86 checkWithCleanup(async () => {
87 mounted.unmount()
88 await act(async () => {
89 await flushPromises()
90 })
91 }, [
92 async () => {
93 await source.cleanup()
94 },
95 ]),
96 }
97 },
98 },
99 reach,
100 )
101 },
102)