Open History to see the last commit
1/**
2 * Source ID reuse contract for React's derived live-query identity.
3 *
4 * A Collection ID names one source object for the lifetime of a mounted
5 * derived-identity hook in one DbClient scope. Re-rendering that hook with a different object under
6 * the same ID must reject before it can return rows from the old source.
7 * Unmounting and cleaning up the old scope permits the ID in a new hook. Two
8 * independent client scopes may use the same ID at the same time.
9 *
10 * Model: each mounted hook remembers the source object first seen for an ID
11 * in each client scope. Same object and fresh ID transitions are legal. A
12 * different object for a remembered ID is rejected. A new hook starts a new
13 * model; switching clients selects that client's remembered bindings.
14 * A render that starts a live query claims its source before a descendant
15 * suspends, because the live query may still own that source until cleanup.
16 * Separate hooks can use same-ID objects: their client-scoped Suspense cache
17 * entries must remain distinct, including before the first hook commits.
18 * A rejected render must release any sync-start deferral it acquired for a
19 * shared client descriptor, so a later direct reader can start that Collection.
20 * The release history grammar crosses every rejection cause (a source ID
21 * collision, a query without a stable IR identity, a descriptor factory that
22 * throws while the query binds its sources, a query the live query rejects
23 * when it compiles, a single-result query in an infinite hook, which pages
24 * many rows, a Suspense query that cannot stream during SSR, a sibling that
25 * throws after the hook returns, and a render that suspends and never
26 * commits), every hook
27 * path (live, infinite, and Suspense, each with derived identity or a
28 * dependency list), and both direct
29 * readers (another hook over the Collection, and `startSyncImmediate()`). The
30 * release must also hold when earlier deferred sync starts throw: each pending
31 * Collection is attempted before the first startup error is rethrown.
32 * The bounded histories below distinguish this law from a hash-only check,
33 * which would miss A(id=x) -> C(id=y) -> B(id=x), a changed predicate, and
34 * two different same-ID sources in one query.
35 *
36 * Driver and observation: render the public hook, then rerender it with each
37 * source. At the rerender boundary, compare a thrown error or the public row.
38 * A nonempty queryKey owns its identity, so a keyed query skips the claim: a
39 * same-ID swap under a changed key reads the new source. The release grammar
40 * below runs dependency-list hook paths too. This does not assert a
41 * process-wide Collection registry or other explicit-key semantics.
42 */
43
44import { act, render, renderHook, waitFor } from '@testing-library/react'
45import {
46 DbClient,
47 SourceCollectionIdReuseError,
48 collectionOptions,
49 eq,
50 gt,
51} from '@tanstack/db'
52import { describe, expect, it, vi } from 'vitest'
53import { Suspense } from 'react'
54import { DbProvider } from '../src/DbProvider'
55import { useLiveQuery } from '../src/useLiveQuery'
56import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
57import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
58import { declareOracle } from '../../db/tests/oracle-declaration'
59import { TestErrorBoundary, source } from './source-id-reuse-support'
60import type { Row } from './source-id-reuse-support'
61
62type Binding = { source: ReturnType<typeof source>; client?: DbClient }
63
64// A prior source with the same ID in this client scope forbids a new object.
65// Pairwise history comparison is independent of the hook's token maps.
66function expectedCollision(history: ReadonlyArray<Binding>, next: Binding) {
67 return history.some(
68 (prior) =>
69 prior.client === next.client &&
70 prior.source.id === next.source.id &&
71 prior.source !== next.source,
72 )
73}
74
75function checkRerender(
76 history: ReadonlyArray<Binding>,
77 next: Binding,
78 rerender: () => void,
79) {
80 if (expectedCollision(history, next)) {
81 expect(rerender).toThrow(SourceCollectionIdReuseError)
82 } else {
83 expect(rerender).not.toThrow()
84 }
85}
86
87declareOracle({
88 check: [checkRerender, checkReleaseHistory],
89 model: [expectedCollision],
90})
91
92/*
93 * Release law. A hook in one DbClient scope first reads only its own source,
94 * then rerenders into a rejected query that also reads a shared descriptor.
95 * The rejected render may defer the shared Collection's sync start, and it
96 * must release that deferral: the source stays unstarted until a direct
97 * reader asks, and that reader then starts it exactly once and reads its row.
98 *
99 * Declared reach: every enumerated history must enter the state the law is
100 * about, a rejected render that materialized the shared descriptor. Each cell
101 * asserts that the descriptor factory ran once before the reader, so a
102 * history that rejects before binding the shared source fails instead of
103 * passing vacuously.
104 */
105type ReleaseStep = { current: ReturnType<typeof source>; reject: boolean }
106
107const releaseCauses: Record<
108 string,
109 (
110 shared: any,
111 failing: any,
112 ) => {
113 rejected: (step: ReleaseStep) => ReleaseStep
114 query: (q: any, step: ReleaseStep, ordered: boolean) => any
115 /** Which hook paths the cause rejects in; all of them by default. */
116 rejectsIn?: (hook: ReleaseHook) => boolean
117 /** The dependency values for a hook with a dependency list. */
118 deps?: (step: ReleaseStep) => Array<unknown>
119 /** Prepare the client, for a cause that depends on its mode. */
120 setup?: (client: DbClient) => void
121 /** Render the rejected step first, for a cause only a mount reaches. */
122 atMount?: boolean
123 /**
124 * What the component does after the hook returns in the rejected step:
125 * throw to an error boundary, or suspend on a promise that never settles.
126 * Either way the render never commits; the hook itself rejected nothing.
127 */
128 afterHook?: `throw` | `suspend`
129 }
130> = {
131 'a source ID collision': (shared) => ({
132 rejected: () => ({
133 current: source(`settings`, `replacement`),
134 reject: true,
135 }),
136 query: (q, step, ordered) =>
137 orderIf(
138 step.reject
139 ? q
140 .from({ settings: step.current })
141 .join({ shared }, ({ settings, shared: row }: any) =>
142 eq(settings.id, row.id),
143 )
144 : q.from({ settings: step.current }),
145 ordered,
146 ),
147 }),
148 'a query without a stable IR identity': (shared) => ({
149 rejected: (step) => ({ ...step, reject: true }),
150 query: (q, step, ordered) =>
151 orderIf(
152 step.reject
153 ? q
154 .from({ settings: step.current })
155 .join({ shared }, ({ settings, shared: row }: any) =>
156 eq(settings.id, row.id),
157 )
158 .fn.where(() => true)
159 : q.from({ settings: step.current }),
160 ordered,
161 ),
162 }),
163 'a descriptor factory that throws': (shared, failing) => ({
164 rejected: (step) => ({ ...step, reject: true }),
165 query: (q, step, ordered) =>
166 orderIf(
167 step.reject
168 ? q
169 .from({ settings: step.current })
170 .join({ shared }, ({ settings, shared: row }: any) =>
171 eq(settings.id, row.id),
172 )
173 .join({ failing }, ({ settings, failing: row }: any) =>
174 eq(settings.id, row.id),
175 )
176 : q.from({ settings: step.current }),
177 ordered,
178 ),
179 }),
180 'a query the live query rejects when it compiles': (shared) => ({
181 rejected: (step) => ({ ...step, reject: true }),
182 // A root scalar select is valid IR that compilation refuses.
183 query: (q, step, ordered) =>
184 step.reject
185 ? orderIf(
186 q
187 .from({ settings: step.current })
188 .join({ shared }, ({ settings, shared: row }: any) =>
189 eq(settings.id, row.id),
190 ),
191 ordered,
192 ).select(({ settings }: any) => settings.value)
193 : orderIf(q.from({ settings: step.current }), ordered),
194 }),
195 'a single-result window query': (shared) => ({
196 rejected: (step) => ({ ...step, reject: true }),
197 query: (q, step, ordered) => {
198 const query = orderIf(
199 step.reject
200 ? q
201 .from({ settings: step.current })
202 .join({ shared }, ({ settings, shared: row }: any) =>
203 eq(settings.id, row.id),
204 )
205 : q.from({ settings: step.current }),
206 ordered,
207 )
208 return step.reject ? query.findOne() : query
209 },
210 // A live query may read one row; an infinite query must page many.
211 rejectsIn: (hook) => hook.ordered,
212 }),
213 'a Suspense query that cannot stream during SSR': (shared) => ({
214 rejected: (step) => ({ ...step, reject: true }),
215 query: (q, step) =>
216 q
217 .from({ settings: step.current })
218 .join({ shared }, ({ settings, shared: row }: any) =>
219 eq(settings.id, row.id),
220 ),
221 // A function dependency gives the stream no stable key.
222 deps: (step) => [step.current, () => step.reject],
223 setup: (client) => client._setSsrStreamingEnabled(true),
224 rejectsIn: (hook) => hook.suspense && hook.usesDeps,
225 atMount: true,
226 }),
227 'a sibling that throws after the hook returns': (shared) => ({
228 rejected: (step) => ({ ...step, reject: true }),
229 query: (q, step, ordered) =>
230 orderIf(
231 step.reject
232 ? q
233 .from({ settings: step.current })
234 .join({ shared }, ({ settings, shared: row }: any) =>
235 eq(settings.id, row.id),
236 )
237 : q.from({ settings: step.current }),
238 ordered,
239 ),
240 afterHook: `throw`,
241 // A Suspense hook that returns has already preloaded its query, which
242 // starts its sources, so no deferral is left to release.
243 rejectsIn: (hook) => !hook.suspense,
244 }),
245 'a render that suspends and never commits': (shared) => ({
246 rejected: (step) => ({ ...step, reject: true }),
247 query: (q, step, ordered) =>
248 orderIf(
249 step.reject
250 ? q
251 .from({ settings: step.current })
252 .join({ shared }, ({ settings, shared: row }: any) =>
253 eq(settings.id, row.id),
254 )
255 : q.from({ settings: step.current }),
256 ordered,
257 ),
258 afterHook: `suspend`,
259 // As above: a Suspense hook's own read is a preload.
260 rejectsIn: (hook) => !hook.suspense,
261 }),
262}
263
264function orderIf(query: any, ordered: boolean) {
265 return ordered ? query.orderBy(({ settings }: any) => settings.rank) : query
266}
267
268type ReleaseHook = {
269 ordered: boolean
270 suspense: boolean
271 usesDeps: boolean
272 use: (query: (q: any) => any, deps: Array<unknown>) => void
273}
274
275const releaseHooks: Record<string, ReleaseHook> = {
276 'useLiveQuery with derived identity': {
277 ordered: false,
278 suspense: false,
279 usesDeps: false,
280 use: (query) => void useLiveQuery(query),
281 },
282 'useLiveQuery with a dependency list': {
283 ordered: false,
284 suspense: false,
285 usesDeps: true,
286 use: (query, deps) => void useLiveQuery(query, deps),
287 },
288 'useLiveInfiniteQuery with derived identity': {
289 ordered: true,
290 suspense: false,
291 usesDeps: false,
292 use: (query) => void useLiveInfiniteQuery(query, { pageSize: 1 }),
293 },
294 'useLiveInfiniteQuery with a dependency list': {
295 ordered: true,
296 suspense: false,
297 usesDeps: true,
298 use: (query, deps) =>
299 void useLiveInfiniteQuery(query, { pageSize: 1 }, deps),
300 },
301 // A config can turn off the reclaim: gcTime 0 or Infinity disables GC, and
302 // startSync false never arms it. A render that never commits must still
303 // release its deferral.
304 'useLiveQuery with gcTime 0': {
305 ordered: false,
306 suspense: false,
307 usesDeps: false,
308 use: (query) => void useLiveQuery({ query, gcTime: 0 }),
309 },
310 'useLiveQuery with gcTime Infinity': {
311 ordered: false,
312 suspense: false,
313 usesDeps: false,
314 use: (query) => void useLiveQuery({ query, gcTime: Infinity }),
315 },
316 'useLiveQuery with startSync false': {
317 ordered: false,
318 suspense: false,
319 usesDeps: false,
320 use: (query) => void useLiveQuery({ query, startSync: false }),
321 },
322 'useLiveSuspenseQuery with derived identity': {
323 ordered: false,
324 suspense: true,
325 usesDeps: false,
326 use: (query) => void useLiveSuspenseQuery(query),
327 },
328 'useLiveSuspenseQuery with a dependency list': {
329 ordered: false,
330 suspense: true,
331 usesDeps: true,
332 use: (query, deps) => void useLiveSuspenseQuery(query, deps),
333 },
334}
335
336// Each reader asks for the source synchronously and returns a read of its
337// row. A rejection has released already, so the demand starts the source at
338// once. A render that never commits releases its deferral when its live
339// query is reclaimed, so the row may arrive after the reader asked.
340const releaseReaders: Record<
341 string,
342 (shared: ReturnType<typeof source>) => () => unknown
343> = {
344 'another hook over the Collection': (shared) => {
345 const reader = renderHook(() => useLiveQuery(shared))
346 return () => reader.result.current.data[0]?.value
347 },
348 'startSyncImmediate()': (shared) => {
349 shared.startSyncImmediate()
350 return () => shared.toArray[0]?.value
351 },
352}
353
354/**
355 * Release driver: runs one rejection history (cause, hook, reader) and checks
356 * when the shared source starts. The law is the release law above: a rejected
357 * render releases its deferral before the reader asks, and a render that never
358 * commits releases it at the reclaim. Each cell of the grammar reaches a
359 * materialized shared descriptor, so the driver asserts that before the reader.
360 */
361let releaseSequence = 0
362async function checkReleaseHistory(
363 makeCause: (typeof releaseCauses)[string],
364 hook: ReleaseHook,
365 read: (typeof releaseReaders)[string],
366) {
367 const client = new DbClient()
368 const id = `release-shared-${releaseSequence++}`
369 let syncStarts = 0
370 let materialized = 0
371 const shared = collectionOptions(
372 id,
373 () => (
374 materialized++,
375 {
376 id,
377 getKey: (row: Row) => row.id,
378 sync: {
379 sync: ({ begin, write, commit, markReady }) => {
380 syncStarts++
381 begin()
382 write({
383 type: `insert`,
384 value: { id: `one`, value: `shared`, rank: 1 },
385 })
386 commit()
387 markReady()
388 },
389 },
390 }
391 ),
392 )
393 const failing = collectionOptions(`${id}-failing`, () => {
394 throw new Error(`descriptor factory failed`)
395 })
396 const cause = makeCause(shared, failing)
397 cause.setup?.(client)
398 const never = new Promise<void>(() => {})
399 function View({ step }: { step: ReleaseStep }) {
400 hook.use(
401 (q) => cause.query(q, step, hook.ordered),
402 cause.deps?.(step) ?? [step.current, step.reject],
403 )
404 if (step.reject && cause.afterHook === `throw`) {
405 throw new Error(`sibling failed`)
406 }
407 if (step.reject && cause.afterHook === `suspend`) throw never
408 return <div>Query</div>
409 }
410 const tree = (step: ReleaseStep) => (
411 <DbProvider client={client}>
412 <TestErrorBoundary>
413 <Suspense fallback={<div>Loading</div>}>
414 <View step={step} />
415 </Suspense>
416 </TestErrorBoundary>
417 </DbProvider>
418 )
419 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
420 try {
421 const initial = {
422 current: source(`settings`, `first`),
423 reject: false,
424 }
425 const root = render(tree(cause.atMount ? cause.rejected(initial) : initial))
426 await act(async () => {})
427 if (!cause.atMount) root.rerender(tree(cause.rejected(initial)))
428 expect(
429 root.getByText(cause.afterHook === `suspend` ? `Loading` : `Rejected`),
430 ).toBeDefined()
431 // Declared reach: the rejected render materialized the shared
432 // descriptor, so it held a deferral the law must release.
433 expect(materialized).toBe(1)
434 // A rejection releases at its render boundary, before the reader.
435 // A render that never commits releases at the reclaim, which the
436 // real GC timer may reach before or after the reader asks.
437 if (!cause.afterHook) expect(syncStarts).toBe(0)
438
439 const value = read(client.collection(shared) as any)
440 if (cause.afterHook) {
441 await waitFor(() => expect(value()).toBe(`shared`))
442 } else {
443 // Released at the render boundary, so the demand started it.
444 expect(syncStarts).toBe(1)
445 await act(async () => {})
446 expect(value()).toBe(`shared`)
447 }
448 expect(syncStarts).toBe(1)
449 } finally {
450 consoleError.mockRestore()
451 }
452}
453
454describe(`React source ID reuse: rejected renders release deferred sync starts`, () => {
455 for (const [causeName, makeCause] of Object.entries(releaseCauses)) {
456 for (const [hookName, hook] of Object.entries(releaseHooks)) {
457 const probe = makeCause(undefined, undefined)
458 if (probe.rejectsIn && !probe.rejectsIn(hook)) continue
459 for (const [readerName, read] of Object.entries(releaseReaders)) {
460 it(`after ${causeName} in ${hookName}, ${readerName} starts the shared source`, () =>
461 checkReleaseHistory(makeCause, hook, read))
462 }
463 }
464 }
465})
466
467describe(`React source ID reuse`, () => {
468 it(`rejects a different active source with the same ID before exposing stale rows`, async () => {
469 const first = source(`settings`, `first`)
470 const second = source(`settings`, `second`)
471 const hook = renderHook(
472 ({ current }) =>
473 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
474 { initialProps: { current: first } },
475 )
476
477 await waitFor(() =>
478 expect(hook.result.current.data[0]?.value).toBe(`first`),
479 )
480 checkRerender([{ source: first }], { source: second }, () =>
481 hook.rerender({ current: second }),
482 )
483 })
484
485 it(`rejects a previously used ID after another source and a query change`, async () => {
486 const first = source(`settings`, `first`)
487 const other = source(`other`, `other`)
488 const second = source(`settings`, `second`)
489 const hook = renderHook(
490 ({ current, minimum }) =>
491 useLiveQuery({
492 query: (q) =>
493 q
494 .from({ settings: current })
495 .where(({ settings }) => gt(settings.rank, minimum)),
496 }),
497 { initialProps: { current: first, minimum: 0 } },
498 )
499
500 await waitFor(() =>
501 expect(hook.result.current.data[0]?.value).toBe(`first`),
502 )
503 act(() => hook.rerender({ current: other, minimum: 0 }))
504 await waitFor(() =>
505 expect(hook.result.current.data[0]?.value).toBe(`other`),
506 )
507 checkRerender(
508 [{ source: first }, { source: other }],
509 { source: second },
510 () => hook.rerender({ current: second, minimum: -1 }),
511 )
512 })
513
514 it(`accepts the same source object and a different source ID`, async () => {
515 const first = source(`settings`, `first`)
516 const other = source(`other`, `other`)
517 const hook = renderHook(
518 ({ current }) =>
519 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
520 { initialProps: { current: first } },
521 )
522
523 await waitFor(() =>
524 expect(hook.result.current.data[0]?.value).toBe(`first`),
525 )
526 checkRerender([{ source: first }], { source: first }, () =>
527 hook.rerender({ current: first }),
528 )
529 expect(hook.result.current.data[0]?.value).toBe(`first`)
530 checkRerender([{ source: first }], { source: other }, () =>
531 hook.rerender({ current: other }),
532 )
533 await waitFor(() =>
534 expect(hook.result.current.data[0]?.value).toBe(`other`),
535 )
536 })
537
538 it(`keeps a mounted hook's ID binding after source cleanup`, async () => {
539 const first = source(`settings`, `first`)
540 const second = source(`settings`, `second`)
541 const hook = renderHook(
542 ({ current }) =>
543 useLiveQuery({ query: (q) => q.from({ settings: current }) }),
544 { initialProps: { current: first } },
545 )
546 await waitFor(() =>
547 expect(hook.result.current.data[0]?.value).toBe(`first`),
548 )
549 await act(async () => first.cleanup({ dependents: true }))
550 checkRerender([{ source: first }], { source: second }, () =>
551 hook.rerender({ current: second }),
552 )
553 })
554
555 it(`remembers each client scope when one mounted hook switches clients`, async () => {
556 const firstClient = new DbClient()
557 const secondClient = new DbClient()
558 const first = source(`settings`, `first`)
559 const otherScope = source(`settings`, `other`)
560 const replacement = source(`settings`, `replacement`)
561 const hook = renderHook(
562 ({ client, current }) =>
563 useLiveQuery({
564 client,
565 query: (q) => q.from({ settings: current }),
566 }),
567 { initialProps: { client: firstClient, current: first } },
568 )
569
570 await waitFor(() =>
571 expect(hook.result.current.data[0]?.value).toBe(`first`),
572 )
573 hook.rerender({ client: secondClient, current: otherScope })
574 await waitFor(() =>
575 expect(hook.result.current.data[0]?.value).toBe(`other`),
576 )
577 checkRerender(
578 [
579 { source: first, client: firstClient },
580 { source: otherScope, client: secondClient },
581 ],
582 { source: replacement, client: firstClient },
583 () => hook.rerender({ client: firstClient, current: replacement }),
584 )
585 })
586
587 it(`rejects same-ID reuse after a suspended render starts a source query`, async () => {
588 const first = source(`first`, `first`)
589 const abandoned = source(`candidate`, `abandoned`)
590 const replacement = source(`candidate`, `replacement`)
591 const never = new Promise<void>(() => {})
592 const View = ({
593 current,
594 suspend,
595 }: {
596 current: typeof first
597 suspend: boolean
598 }) => {
599 const { data } = useLiveQuery({
600 query: (q) => q.from({ settings: current }),
601 })
602 if (suspend) throw never
603 return <div>{data[0]?.value}</div>
604 }
605 const root = render(
606 <Suspense fallback={<div>Loading</div>}>
607 <View current={first} suspend={false} />
608 </Suspense>,
609 )
610 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
611
612 root.rerender(
613 <Suspense fallback={<div>Loading</div>}>
614 <View current={abandoned} suspend={true} />
615 </Suspense>,
616 )
617 checkRerender(
618 [{ source: first }, { source: abandoned }],
619 { source: replacement },
620 () =>
621 root.rerender(
622 <Suspense fallback={<div>Loading</div>}>
623 <View current={replacement} suspend={false} />
624 </Suspense>,
625 ),
626 )
627 })
628})
629
630/**
631 * ## useLiveInfiniteQuery
632 *
633 * The infinite hook derives its identity the same way, and keeps the window
634 * collection built by its latest render for a second render before commit.
635 * That cache is keyed by derived identity, which names sources by ID, so the
636 * same law applies: a different same-ID source must reject before the hook
637 * can publish the old source's rows, from a committed or a suspended render.
638 * This driver reuses the model above with the bounded histories that
639 * distinguish the law from a hash-only check.
640 */
641describe(`React source ID reuse: useLiveInfiniteQuery`, () => {
642 const useInfinite = (current: ReturnType<typeof source>) =>
643 useLiveInfiniteQuery(
644 (q) =>
645 q.from({ settings: current }).orderBy(({ settings }) => settings.rank),
646 { pageSize: 1 },
647 )
648
649 it(`rejects a different active source with the same ID before exposing stale rows`, async () => {
650 const first = source(`settings`, `first`)
651 const second = source(`settings`, `second`)
652 const hook = renderHook(({ current }) => useInfinite(current), {
653 initialProps: { current: first },
654 })
655 await waitFor(() =>
656 expect(hook.result.current.data[0]?.value).toBe(`first`),
657 )
658 checkRerender([{ source: first }], { source: second }, () =>
659 hook.rerender({ current: second }),
660 )
661 })
662
663 it(`rejects a previously used ID after another source`, async () => {
664 const first = source(`settings`, `first`)
665 const other = source(`other`, `other`)
666 const second = source(`settings`, `second`)
667 const hook = renderHook(({ current }) => useInfinite(current), {
668 initialProps: { current: first },
669 })
670 await waitFor(() =>
671 expect(hook.result.current.data[0]?.value).toBe(`first`),
672 )
673 act(() => hook.rerender({ current: other }))
674 await waitFor(() =>
675 expect(hook.result.current.data[0]?.value).toBe(`other`),
676 )
677 checkRerender(
678 [{ source: first }, { source: other }],
679 { source: second },
680 () => hook.rerender({ current: second }),
681 )
682 })
683
684 it(`accepts the same source object and a different source ID`, async () => {
685 const first = source(`settings`, `first`)
686 const other = source(`other`, `other`)
687 const hook = renderHook(({ current }) => useInfinite(current), {
688 initialProps: { current: first },
689 })
690 await waitFor(() =>
691 expect(hook.result.current.data[0]?.value).toBe(`first`),
692 )
693 checkRerender([{ source: first }], { source: first }, () =>
694 hook.rerender({ current: first }),
695 )
696 checkRerender([{ source: first }], { source: other }, () =>
697 hook.rerender({ current: other }),
698 )
699 await waitFor(() =>
700 expect(hook.result.current.data[0]?.value).toBe(`other`),
701 )
702 })
703
704 it(`rejects same-ID reuse after a suspended render starts a source query`, async () => {
705 const first = source(`first`, `first`)
706 const abandoned = source(`candidate`, `abandoned`)
707 const replacement = source(`candidate`, `replacement`)
708 const never = new Promise<void>(() => {})
709 const View = ({
710 current,
711 suspend,
712 }: {
713 current: typeof first
714 suspend: boolean
715 }) => {
716 const { data } = useInfinite(current)
717 if (suspend) throw never
718 return <div>{data[0]?.value}</div>
719 }
720 const root = render(
721 <Suspense fallback={<div>Loading</div>}>
722 <View current={first} suspend={false} />
723 </Suspense>,
724 )
725 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
726 root.rerender(
727 <Suspense fallback={<div>Loading</div>}>
728 <View current={abandoned} suspend={true} />
729 </Suspense>,
730 )
731 checkRerender(
732 [{ source: first }, { source: abandoned }],
733 { source: replacement },
734 () =>
735 root.rerender(
736 <Suspense fallback={<div>Loading</div>}>
737 <View current={replacement} suspend={false} />
738 </Suspense>,
739 ),
740 )
741 })
742})