Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

useLiveQuery.test.tsx

1,447 lines38.7 KB

1import { describe, expect, it } from "vitest"
2import { act, renderHook, waitFor } from "@testing-library/react"
3import {
4 Query,
5 count,
6 createCollection,
7 createLiveQueryCollection,
8 createOptimisticAction,
9 eq,
10 gt,
11} from "@tanstack/db"
12import { useEffect } from "react"
13import { useLiveQuery } from "../src/useLiveQuery"
14import { mockSyncCollectionOptions } from "../../db/tests/utils"
15​
16type Person = {
17 id: string
18 name: string
19 age: number
20 email: string
21 isActive: boolean
22 team: string
24​
25type Issue = {
26 id: string
27 title: string
28 description: string
29 userId: string
31​
32const initialPersons: Array<Person> = [
33 {
34 id: `1`,
35 name: `John Doe`,
36 age: 30,
37 email: `john.doe@example.com`,
38 isActive: true,
39 team: `team1`,
40 },
41 {
42 id: `2`,
43 name: `Jane Doe`,
44 age: 25,
45 email: `jane.doe@example.com`,
46 isActive: true,
47 team: `team2`,
48 },
49 {
50 id: `3`,
51 name: `John Smith`,
52 age: 35,
53 email: `john.smith@example.com`,
54 isActive: true,
55 team: `team1`,
56 },
58​
59const initialIssues: Array<Issue> = [
60 {
61 id: `1`,
62 title: `Issue 1`,
63 description: `Issue 1 description`,
64 userId: `1`,
65 },
66 {
67 id: `2`,
68 title: `Issue 2`,
69 description: `Issue 2 description`,
70 userId: `2`,
71 },
72 {
73 id: `3`,
74 title: `Issue 3`,
75 description: `Issue 3 description`,
76 userId: `1`,
77 },
79​
80describe(`Query Collections`, () => {
81 it(`should work with basic collection and select`, async () => {
82 const collection = createCollection(
83 mockSyncCollectionOptions<Person>({
84 id: `test-persons`,
85 getKey: (person: Person) => person.id,
86 initialData: initialPersons,
87 })
88 )
89​
90 const { result } = renderHook(() => {
91 return useLiveQuery((q) =>
92 q
93 .from({ persons: collection })
94 .where(({ persons }) => gt(persons.age, 30))
95 .select(({ persons }) => ({
96 id: persons.id,
97 name: persons.name,
98 age: persons.age,
99 }))
100 )
101 })
102​
103 // Wait for collection to sync and state to update
104 await waitFor(() => {
105 expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
106 })
107 expect(result.current.data).toHaveLength(1)
108​
109 const johnSmith = result.current.data[0]
110 expect(johnSmith).toMatchObject({
111 id: `3`,
112 name: `John Smith`,
113 age: 35,
114 })
115 })
116​
117 it(`should keep stable ref`, async () => {
118 const collection = createCollection(
119 mockSyncCollectionOptions<Person>({
120 id: `test-persons`,
121 getKey: (person: Person) => person.id,
122 initialData: initialPersons,
123 })
124 )
125​
126 const { result, rerender } = renderHook(() => {
127 return useLiveQuery((q) =>
128 q
129 .from({ persons: collection })
130 .where(({ persons }) => gt(persons.age, 30))
131 .select(({ persons }) => ({
132 id: persons.id,
133 name: persons.name,
134 age: persons.age,
135 }))
136 )
137 })
138​
139 // Wait for collection to sync and state to update
140 await waitFor(() => {
141 expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
142 })
143​
144 const data1 = result.current.data
145 expect(result.current.data).toHaveLength(1)
146​
147 rerender()
148​
149 const data2 = result.current.data
150​
151 // Passes cause the underlying objects are stable
152 expect(data1).toEqual(data2)
153 expect(data1[0]).toBe(data2[0])
154​
155 // Fails cause array isn't
156 expect(data1).toBe(data2)
157 })
158​
159 it(`should be able to query a collection with live updates`, async () => {
160 const collection = createCollection(
161 mockSyncCollectionOptions<Person>({
162 id: `test-persons-2`,
163 getKey: (person: Person) => person.id,
164 initialData: initialPersons,
165 })
166 )
167​
168 const { result } = renderHook(() => {
169 return useLiveQuery((q) =>
170 q
171 .from({ collection })
172 .where(({ collection: c }) => gt(c.age, 30))
173 .select(({ collection: c }) => ({
174 id: c.id,
175 name: c.name,
176 }))
177 .orderBy(({ collection: c }) => c.id, `asc`)
178 )
179 })
180​
181 // Wait for collection to sync
182 await waitFor(() => {
183 expect(result.current.state.size).toBe(1)
184 })
185 expect(result.current.state.get(`3`)).toMatchObject({
186 id: `3`,
187 name: `John Smith`,
188 })
189​
190 expect(result.current.data.length).toBe(1)
191 expect(result.current.data[0]).toMatchObject({
192 id: `3`,
193 name: `John Smith`,
194 })
195​
196 // Insert a new person using the proper utils pattern
197 act(() => {
198 collection.utils.begin()
199 collection.utils.write({
200 type: `insert`,
201 value: {
202 id: `4`,
203 name: `Kyle Doe`,
204 age: 40,
205 email: `kyle.doe@example.com`,
206 isActive: true,
207 team: `team1`,
208 },
209 })
210 collection.utils.commit()
211 })
212​
213 await waitFor(() => {
214 expect(result.current.state.size).toBe(2)
215 })
216 expect(result.current.state.get(`3`)).toMatchObject({
217 id: `3`,
218 name: `John Smith`,
219 })
220 expect(result.current.state.get(`4`)).toMatchObject({
221 id: `4`,
222 name: `Kyle Doe`,
223 })
224​
225 expect(result.current.data.length).toBe(2)
226 expect(result.current.data).toEqual(
227 expect.arrayContaining([
228 expect.objectContaining({
229 id: `3`,
230 name: `John Smith`,
231 }),
232 expect.objectContaining({
233 id: `4`,
234 name: `Kyle Doe`,
235 }),
236 ])
237 )
238​
239 // Update the person
240 act(() => {
241 collection.utils.begin()
242 collection.utils.write({
243 type: `update`,
244 value: {
245 id: `4`,
246 name: `Kyle Doe 2`,
247 age: 40,
248 email: `kyle.doe@example.com`,
249 isActive: true,
250 team: `team1`,
251 },
252 })
253 collection.utils.commit()
254 })
255​
256 await waitFor(() => {
257 expect(result.current.state.size).toBe(2)
258 })
259 expect(result.current.state.get(`4`)).toMatchObject({
260 id: `4`,
261 name: `Kyle Doe 2`,
262 })
263​
264 expect(result.current.data.length).toBe(2)
265 expect(result.current.data).toEqual(
266 expect.arrayContaining([
267 expect.objectContaining({
268 id: `3`,
269 name: `John Smith`,
270 }),
271 expect.objectContaining({
272 id: `4`,
273 name: `Kyle Doe 2`,
274 }),
275 ])
276 )
277​
278 // Delete the person
279 act(() => {
280 collection.utils.begin()
281 collection.utils.write({
282 type: `delete`,
283 value: {
284 id: `4`,
285 name: `Kyle Doe 2`,
286 age: 40,
287 email: `kyle.doe@example.com`,
288 isActive: true,
289 team: `team1`,
290 },
291 })
292 collection.utils.commit()
293 })
294​
295 await waitFor(() => {
296 expect(result.current.state.size).toBe(1)
297 })
298 expect(result.current.state.get(`4`)).toBeUndefined()
299​
300 expect(result.current.data.length).toBe(1)
301 expect(result.current.data[0]).toMatchObject({
302 id: `3`,
303 name: `John Smith`,
304 })
305 })
306​
307 it(`should join collections and return combined results with live updates`, async () => {
308 // Create person collection
309 const personCollection = createCollection(
310 mockSyncCollectionOptions<Person>({
311 id: `person-collection-test`,
312 getKey: (person: Person) => person.id,
313 initialData: initialPersons,
314 })
315 )
316​
317 // Create issue collection
318 const issueCollection = createCollection(
319 mockSyncCollectionOptions<Issue>({
320 id: `issue-collection-test`,
321 getKey: (issue: Issue) => issue.id,
322 initialData: initialIssues,
323 })
324 )
325​
326 const { result } = renderHook(() => {
327 return useLiveQuery((q) =>
328 q
329 .from({ issues: issueCollection })
330 .join({ persons: personCollection }, ({ issues, persons }) =>
331 eq(issues.userId, persons.id)
332 )
333 .select(({ issues, persons }) => ({
334 id: issues.id,
335 title: issues.title,
336 name: persons.name,
337 }))
338 )
339 })
340​
341 // Wait for collections to sync
342 await waitFor(() => {
343 expect(result.current.state.size).toBe(3)
344 })
345​
346 // Verify that we have the expected joined results
347​
348 expect(result.current.state.get(`[1,1]`)).toMatchObject({
349 id: `1`,
350 name: `John Doe`,
351 title: `Issue 1`,
352 })
353​
354 expect(result.current.state.get(`[2,2]`)).toMatchObject({
355 id: `2`,
356 name: `Jane Doe`,
357 title: `Issue 2`,
358 })
359​
360 expect(result.current.state.get(`[3,1]`)).toMatchObject({
361 id: `3`,
362 name: `John Doe`,
363 title: `Issue 3`,
364 })
365​
366 // Add a new issue for user 2
367 act(() => {
368 issueCollection.utils.begin()
369 issueCollection.utils.write({
370 type: `insert`,
371 value: {
372 id: `4`,
373 title: `Issue 4`,
374 description: `Issue 4 description`,
375 userId: `2`,
376 },
377 })
378 issueCollection.utils.commit()
379 })
380​
381 await waitFor(() => {
382 expect(result.current.state.size).toBe(4)
383 })
384 expect(result.current.state.get(`[4,2]`)).toMatchObject({
385 id: `4`,
386 name: `Jane Doe`,
387 title: `Issue 4`,
388 })
389​
390 // Update an issue we're already joined with
391 act(() => {
392 issueCollection.utils.begin()
393 issueCollection.utils.write({
394 type: `update`,
395 value: {
396 id: `2`,
397 title: `Updated Issue 2`,
398 description: `Issue 2 description`,
399 userId: `2`,
400 },
401 })
402 issueCollection.utils.commit()
403 })
404​
405 await waitFor(() => {
406 // The updated title should be reflected in the joined results
407 expect(result.current.state.get(`[2,2]`)).toMatchObject({
408 id: `2`,
409 name: `Jane Doe`,
410 title: `Updated Issue 2`,
411 })
412 })
413​
414 // Delete an issue
415 act(() => {
416 issueCollection.utils.begin()
417 issueCollection.utils.write({
418 type: `delete`,
419 value: {
420 id: `3`,
421 title: `Issue 3`,
422 description: `Issue 3 description`,
423 userId: `1`,
424 },
425 })
426 issueCollection.utils.commit()
427 })
428​
429 await new Promise((resolve) => setTimeout(resolve, 10))
430​
431 // After deletion, issue 3 should no longer have a joined result
432 expect(result.current.state.get(`[3,1]`)).toBeUndefined()
433 expect(result.current.state.size).toBe(3)
434 })
435​
436 it(`should recompile query when parameters change and change results`, async () => {
437 const collection = createCollection(
438 mockSyncCollectionOptions<Person>({
439 id: `params-change-test`,
440 getKey: (person: Person) => person.id,
441 initialData: initialPersons,
442 })
443 )
444​
445 const { result, rerender } = renderHook(
446 ({ minAge }: { minAge: number }) => {
447 return useLiveQuery(
448 (q) =>
449 q
450 .from({ collection })
451 .where(({ collection: c }) => gt(c.age, minAge))
452 .select(({ collection: c }) => ({
453 id: c.id,
454 name: c.name,
455 age: c.age,
456 })),
457 [minAge]
458 )
459 },
460 { initialProps: { minAge: 30 } }
461 )
462​
463 // Wait for collection to sync
464 await new Promise((resolve) => setTimeout(resolve, 10))
465​
466 // Initially should return only people older than 30
467 expect(result.current.state.size).toBe(1)
468 expect(result.current.state.get(`3`)).toMatchObject({
469 id: `3`,
470 name: `John Smith`,
471 age: 35,
472 })
473​
474 // Change the parameter to include more people
475 act(() => {
476 rerender({ minAge: 20 })
477 })
478​
479 await new Promise((resolve) => setTimeout(resolve, 10))
480​
481 // Now should return all people as they're all older than 20
482 expect(result.current.state.size).toBe(3)
483 expect(result.current.state.get(`1`)).toMatchObject({
484 id: `1`,
485 name: `John Doe`,
486 age: 30,
487 })
488 expect(result.current.state.get(`2`)).toMatchObject({
489 id: `2`,
490 name: `Jane Doe`,
491 age: 25,
492 })
493 expect(result.current.state.get(`3`)).toMatchObject({
494 id: `3`,
495 name: `John Smith`,
496 age: 35,
497 })
498​
499 // Change to exclude everyone
500 act(() => {
501 rerender({ minAge: 50 })
502 })
503​
504 await new Promise((resolve) => setTimeout(resolve, 10))
505​
506 // Should now be empty
507 expect(result.current.state.size).toBe(0)
508 })
509​
510 it(`should stop old query when parameters change`, async () => {
511 const collection = createCollection(
512 mockSyncCollectionOptions<Person>({
513 id: `stop-query-test`,
514 getKey: (person: Person) => person.id,
515 initialData: initialPersons,
516 })
517 )
518​
519 const { result, rerender } = renderHook(
520 ({ minAge }: { minAge: number }) => {
521 return useLiveQuery(
522 (q) =>
523 q
524 .from({ collection })
525 .where(({ collection: c }) => gt(c.age, minAge))
526 .select(({ collection: c }) => ({
527 id: c.id,
528 name: c.name,
529 })),
530 [minAge]
531 )
532 },
533 { initialProps: { minAge: 30 } }
534 )
535​
536 // Wait for collection to sync
537 await new Promise((resolve) => setTimeout(resolve, 10))
538​
539 // Initial query should return only people older than 30
540 expect(result.current.state.size).toBe(1)
541 expect(result.current.state.get(`3`)).toMatchObject({
542 id: `3`,
543 name: `John Smith`,
544 })
545​
546 // Change the parameter to include more people
547 act(() => {
548 rerender({ minAge: 25 })
549 })
550​
551 await new Promise((resolve) => setTimeout(resolve, 10))
552​
553 // Query should now return all people older than 25
554 expect(result.current.state.size).toBe(2)
555 expect(result.current.state.get(`1`)).toMatchObject({
556 id: `1`,
557 name: `John Doe`,
558 })
559 expect(result.current.state.get(`3`)).toMatchObject({
560 id: `3`,
561 name: `John Smith`,
562 })
563​
564 // Change to a value that excludes everyone
565 act(() => {
566 rerender({ minAge: 50 })
567 })
568​
569 await new Promise((resolve) => setTimeout(resolve, 10))
570​
571 // Should now be empty
572 expect(result.current.state.size).toBe(0)
573 })
574​
575 it(`should be able to query a result collection with live updates`, async () => {
576 const collection = createCollection(
577 mockSyncCollectionOptions<Person>({
578 id: `optimistic-changes-test`,
579 getKey: (person: Person) => person.id,
580 initialData: initialPersons,
581 })
582 )
583​
584 // Initial query
585 const { result } = renderHook(() => {
586 return useLiveQuery((q) =>
587 q
588 .from({ collection })
589 .where(({ collection: c }) => gt(c.age, 30))
590 .select(({ collection: c }) => ({
591 id: c.id,
592 name: c.name,
593 team: c.team,
594 }))
595 .orderBy(({ collection: c }) => c.id, `asc`)
596 )
597 })
598​
599 // Wait for collection to sync
600 await new Promise((resolve) => setTimeout(resolve, 10))
601​
602 // Grouped query derived from initial query
603 const { result: groupedResult } = renderHook(() => {
604 return useLiveQuery((q) =>
605 q
606 .from({ queryResult: result.current.collection })
607 .groupBy(({ queryResult }) => queryResult.team)
608 .select(({ queryResult }) => ({
609 team: queryResult.team,
610 count: count(queryResult.id),
611 }))
612 )
613 })
614​
615 // Wait for grouped query to sync
616 await new Promise((resolve) => setTimeout(resolve, 10))
617​
618 // Verify initial grouped results
619 expect(groupedResult.current.state.size).toBe(1)
620 const teamResult = Array.from(groupedResult.current.state.values())[0]
621 expect(teamResult).toMatchObject({
622 team: `team1`,
623 count: 1,
624 })
625​
626 // Insert two new users in different teams
627 act(() => {
628 collection.utils.begin()
629 collection.utils.write({
630 type: `insert`,
631 value: {
632 id: `5`,
633 name: `Sarah Jones`,
634 age: 32,
635 email: `sarah.jones@example.com`,
636 isActive: true,
637 team: `team1`,
638 },
639 })
640 collection.utils.write({
641 type: `insert`,
642 value: {
643 id: `6`,
644 name: `Mike Wilson`,
645 age: 38,
646 email: `mike.wilson@example.com`,
647 isActive: true,
648 team: `team2`,
649 },
650 })
651 collection.utils.commit()
652 })
653​
654 await new Promise((resolve) => setTimeout(resolve, 10))
655​
656 // Verify the grouped results include the new team members
657 expect(groupedResult.current.state.size).toBe(2)
658​
659 const groupedResults = Array.from(groupedResult.current.state.values())
660 const team1Result = groupedResults.find((r) => r.team === `team1`)
661 const team2Result = groupedResults.find((r) => r.team === `team2`)
662​
663 expect(team1Result).toMatchObject({
664 team: `team1`,
665 count: 2, // John Smith + Sarah Jones
666 })
667 expect(team2Result).toMatchObject({
668 team: `team2`,
669 count: 1, // Mike Wilson
670 })
671 })
672​
673 it(`optimistic state is dropped after commit`, async () => {
674 // Track renders and states
675 const renderStates: Array<{
676 stateSize: number
677 hasTempKey: boolean
678 hasPermKey: boolean
679 timestamp: number
680 }> = []
681​
682 // Create person collection
683 const personCollection = createCollection(
684 mockSyncCollectionOptions<Person>({
685 id: `person-collection-test-bug`,
686 getKey: (person: Person) => person.id,
687 initialData: initialPersons,
688 })
689 )
690​
691 // Create issue collection
692 const issueCollection = createCollection(
693 mockSyncCollectionOptions<Issue>({
694 id: `issue-collection-test-bug`,
695 getKey: (issue: Issue) => issue.id,
696 initialData: initialIssues,
697 })
698 )
699​
700 // Render the hook with a query that joins persons and issues
701 const { result } = renderHook(() => {
702 const queryResult = useLiveQuery((q) =>
703 q
704 .from({ issues: issueCollection })
705 .join({ persons: personCollection }, ({ issues, persons }) =>
706 eq(issues.userId, persons.id)
707 )
708 .select(({ issues, persons }) => ({
709 id: issues.id,
710 title: issues.title,
711 name: persons.name,
712 }))
713 )
714​
715 // Track each render state
716 useEffect(() => {
717 renderStates.push({
718 stateSize: queryResult.state.size,
719 hasTempKey: queryResult.state.has(`[temp-key,1]`),
720 hasPermKey: queryResult.state.has(`[4,1]`),
721 timestamp: Date.now(),
722 })
723 }, [queryResult.state])
724​
725 return queryResult
726 })
727​
728 // Wait for collections to sync and verify initial state
729 await waitFor(() => {
730 expect(result.current.state.size).toBe(3)
731 })
732​
733 // Reset render states array for clarity in the remaining test
734 renderStates.length = 0
735​
736 // Create an optimistic action for adding issues
737 type AddIssueInput = {
738 title: string
739 description: string
740 userId: string
741 }
742​
743 const addIssue = createOptimisticAction<AddIssueInput>({
744 onMutate: (issueInput) => {
745 // Optimistically insert with temporary key
746 issueCollection.insert({
747 id: `temp-key`,
748 title: issueInput.title,
749 description: issueInput.description,
750 userId: issueInput.userId,
751 })
752 },
753 mutationFn: async (issueInput) => {
754 // Simulate server persistence - in a real app, this would be an API call
755 await new Promise((resolve) => setTimeout(resolve, 10)) // Simulate network delay
756​
757 // After "server" responds, update the collection with permanent ID using utils
758 // Note: This act() is inside the mutationFn and handles the async server response
759 act(() => {
760 issueCollection.utils.begin()
761 issueCollection.utils.write({
762 type: `delete`,
763 value: {
764 id: `temp-key`,
765 title: issueInput.title,
766 description: issueInput.description,
767 userId: issueInput.userId,
768 },
769 })
770 issueCollection.utils.write({
771 type: `insert`,
772 value: {
773 id: `4`, // Use the permanent ID
774 title: issueInput.title,
775 description: issueInput.description,
776 userId: issueInput.userId,
777 },
778 })
779 issueCollection.utils.commit()
780 })
781​
782 return { success: true, id: `4` }
783 },
784 })
785​
786 // Perform optimistic insert of a new issue
787 let transaction: any
788 act(() => {
789 transaction = addIssue({
790 title: `New Issue`,
791 description: `New Issue Description`,
792 userId: `1`,
793 })
794 })
795​
796 await waitFor(() => {
797 // Verify optimistic state is immediately reflected
798 expect(result.current.state.size).toBe(4)
799 })
800 expect(result.current.state.get(`[temp-key,1]`)).toMatchObject({
801 id: `temp-key`,
802 name: `John Doe`,
803 title: `New Issue`,
804 })
805 expect(result.current.state.get(`[4,1]`)).toBeUndefined()
806​
807 // Wait for the transaction to be committed
808 await transaction.isPersisted.promise
809​
810 await waitFor(() => {
811 // Wait for the permanent key to appear
812 expect(result.current.state.get(`[4,1]`)).toBeDefined()
813 })
814​
815 // Check if we had any render where the temp key was removed but the permanent key wasn't added yet
816 const hadFlicker = renderStates.some(
817 (state) => !state.hasTempKey && !state.hasPermKey && state.stateSize === 3
818 )
819​
820 expect(hadFlicker).toBe(false)
821​
822 // Verify the temporary key is replaced by the permanent one
823 expect(result.current.state.size).toBe(4)
824 expect(result.current.state.get(`[temp-key,1]`)).toBeUndefined()
825 expect(result.current.state.get(`[4,1]`)).toMatchObject({
826 id: `4`,
827 name: `John Doe`,
828 title: `New Issue`,
829 })
830 })
831​
832 it(`should accept pre-created live query collection`, async () => {
833 const collection = createCollection(
834 mockSyncCollectionOptions<Person>({
835 id: `pre-created-collection-test`,
836 getKey: (person: Person) => person.id,
837 initialData: initialPersons,
838 })
839 )
840​
841 // Create a live query collection beforehand
842 const liveQueryCollection = createLiveQueryCollection({
843 query: (q) =>
844 q
845 .from({ persons: collection })
846 .where(({ persons }) => gt(persons.age, 30))
847 .select(({ persons }) => ({
848 id: persons.id,
849 name: persons.name,
850 age: persons.age,
851 })),
852 startSync: true,
853 })
854​
855 const { result } = renderHook(() => {
856 return useLiveQuery(liveQueryCollection)
857 })
858​
859 // Wait for collection to sync and state to update
860 await waitFor(() => {
861 expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
862 })
863 expect(result.current.data).toHaveLength(1)
864​
865 const johnSmith = result.current.data[0]
866 expect(johnSmith).toMatchObject({
867 id: `3`,
868 name: `John Smith`,
869 age: 35,
870 })
871​
872 // Verify that the returned collection is the same instance
873 expect(result.current.collection).toBe(liveQueryCollection)
874 })
875​
876 it(`should switch to a different pre-created live query collection when changed`, async () => {
877 const collection1 = createCollection(
878 mockSyncCollectionOptions<Person>({
879 id: `collection-1`,
880 getKey: (person: Person) => person.id,
881 initialData: initialPersons,
882 })
883 )
884​
885 const collection2 = createCollection(
886 mockSyncCollectionOptions<Person>({
887 id: `collection-2`,
888 getKey: (person: Person) => person.id,
889 initialData: [
890 {
891 id: `4`,
892 name: `Alice Cooper`,
893 age: 45,
894 email: `alice.cooper@example.com`,
895 isActive: true,
896 team: `team3`,
897 },
898 {
899 id: `5`,
900 name: `Bob Dylan`,
901 age: 50,
902 email: `bob.dylan@example.com`,
903 isActive: true,
904 team: `team3`,
905 },
906 ],
907 })
908 )
909​
910 // Create two different live query collections
911 const liveQueryCollection1 = createLiveQueryCollection({
912 query: (q) =>
913 q
914 .from({ persons: collection1 })
915 .where(({ persons }) => gt(persons.age, 30))
916 .select(({ persons }) => ({
917 id: persons.id,
918 name: persons.name,
919 })),
920 startSync: true,
921 })
922​
923 const liveQueryCollection2 = createLiveQueryCollection({
924 query: (q) =>
925 q
926 .from({ persons: collection2 })
927 .where(({ persons }) => gt(persons.age, 40))
928 .select(({ persons }) => ({
929 id: persons.id,
930 name: persons.name,
931 })),
932 startSync: true,
933 })
934​
935 const { result, rerender } = renderHook(
936 ({ collection }: { collection: any }) => {
937 return useLiveQuery(collection)
938 },
939 { initialProps: { collection: liveQueryCollection1 } }
940 )
941​
942 // Wait for first collection to sync
943 await waitFor(() => {
944 expect(result.current.state.size).toBe(1) // Only John Smith from collection1
945 })
946 expect(result.current.state.get(`3`)).toMatchObject({
947 id: `3`,
948 name: `John Smith`,
949 })
950 expect(result.current.collection).toBe(liveQueryCollection1)
951​
952 // Switch to the second collection
953 act(() => {
954 rerender({ collection: liveQueryCollection2 })
955 })
956​
957 // Wait for second collection to sync
958 await waitFor(() => {
959 expect(result.current.state.size).toBe(2) // Alice and Bob from collection2
960 })
961 expect(result.current.state.get(`4`)).toMatchObject({
962 id: `4`,
963 name: `Alice Cooper`,
964 })
965 expect(result.current.state.get(`5`)).toMatchObject({
966 id: `5`,
967 name: `Bob Dylan`,
968 })
969 expect(result.current.collection).toBe(liveQueryCollection2)
970​
971 // Verify we no longer have data from the first collection
972 expect(result.current.state.get(`3`)).toBeUndefined()
973 })
974​
975 it(`should accept a config object with a pre-built QueryBuilder instance`, async () => {
976 const collection = createCollection(
977 mockSyncCollectionOptions<Person>({
978 id: `test-persons-config-querybuilder`,
979 getKey: (person: Person) => person.id,
980 initialData: initialPersons,
981 })
982 )
983​
984 // Create a QueryBuilder instance beforehand
985 const queryBuilder = new Query()
986 .from({ persons: collection })
987 .where(({ persons }) => gt(persons.age, 30))
988 .select(({ persons }) => ({
989 id: persons.id,
990 name: persons.name,
991 age: persons.age,
992 }))
993​
994 const { result } = renderHook(() => {
995 return useLiveQuery({ query: queryBuilder })
996 })
997​
998 // Wait for collection to sync and state to update
999 await waitFor(() => {
1000 expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
1001 })
1002 expect(result.current.data).toHaveLength(1)
1003​
1004 const johnSmith = result.current.data[0]
1005 expect(johnSmith).toMatchObject({
1006 id: `3`,
1007 name: `John Smith`,
1008 age: 35,
1009 })
1010 })
1011​
1012 describe(`isLoaded property`, () => {
1013 it(`should be true initially and false after collection is ready`, async () => {
1014 let beginFn: (() => void) | undefined
1015 let commitFn: (() => void) | undefined
1016​
1017 // Create a collection that doesn't start sync immediately
1018 const collection = createCollection<Person>({
1019 id: `has-loaded-test`,
1020 getKey: (person: Person) => person.id,
1021 startSync: false, // Don't start sync immediately
1022 sync: {
1023 sync: ({ begin, commit, markReady }) => {
1024 beginFn = begin
1025 commitFn = () => {
1026 commit()
1027 markReady()
1029 // Don't call begin/commit immediately
1030 },
1031 },
1032 onInsert: async () => {},
1033 onUpdate: async () => {},
1034 onDelete: async () => {},
1035 })
1036​
1037 const { result } = renderHook(() => {
1038 return useLiveQuery((q) =>
1040 .from({ persons: collection })
1041 .where(({ persons }) => gt(persons.age, 30))
1042 .select(({ persons }) => ({
1043 id: persons.id,
1044 name: persons.name,
1045 }))
1047 })
1048​
1049 // Initially isLoading should be true
1050 expect(result.current.isLoading).toBe(true)
1051​
1052 // Start sync manually
1053 act(() => {
1054 collection.preload()
1055 })
1056​
1057 // Trigger the first commit to make collection ready
1058 act(() => {
1059 if (beginFn && commitFn) {
1060 beginFn()
1061 commitFn()
1063 })
1064​
1065 // Insert data
1066 act(() => {
1067 collection.insert({
1068 id: `1`,
1069 name: `John Doe`,
1070 age: 35,
1071 email: `john.doe@example.com`,
1072 isActive: true,
1073 team: `team1`,
1074 })
1075 })
1076​
1077 // Wait for collection to become ready
1078 await waitFor(() => {
1079 expect(result.current.isLoading).toBe(false)
1080 })
1081 // Note: Data may not appear immediately due to live query evaluation timing
1082 // The main test is that isLoading transitions from true to false
1083 })
1084​
1085 it(`should be false for pre-created collections that are already syncing`, async () => {
1086 const collection = createCollection(
1087 mockSyncCollectionOptions<Person>({
1088 id: `pre-created-has-loaded-test`,
1089 getKey: (person: Person) => person.id,
1090 initialData: initialPersons,
1091 })
1093​
1094 // Create a live query collection that's already syncing
1095 const liveQueryCollection = createLiveQueryCollection({
1096 query: (q) =>
1098 .from({ persons: collection })
1099 .where(({ persons }) => gt(persons.age, 30))
1100 .select(({ persons }) => ({
1101 id: persons.id,
1102 name: persons.name,
1103 })),
1104 startSync: true,
1105 })
1106​
1107 // Wait a bit for the collection to start syncing
1108 await new Promise((resolve) => setTimeout(resolve, 10))
1109​
1110 const { result } = renderHook(() => {
1111 return useLiveQuery(liveQueryCollection)
1112 })
1113​
1114 // For pre-created collections that are already syncing, isLoading should be true
1115 expect(result.current.isLoading).toBe(false)
1116 expect(result.current.state.size).toBe(1)
1117 })
1118​
1119 it(`should update isLoading when collection status changes`, async () => {
1120 let beginFn: (() => void) | undefined
1121 let commitFn: (() => void) | undefined
1122 let markReadyFn: (() => void) | undefined
1123​
1124 const collection = createCollection<Person>({
1125 id: `status-change-has-loaded-test`,
1126 getKey: (person: Person) => person.id,
1127 startSync: false,
1128 sync: {
1129 sync: ({ begin, commit, markReady }) => {
1130 beginFn = begin
1131 commitFn = commit
1132 markReadyFn = markReady
1133 // Don't sync immediately
1134 },
1135 },
1136 onInsert: async () => {},
1137 onUpdate: async () => {},
1138 onDelete: async () => {},
1139 })
1140​
1141 const { result } = renderHook(() => {
1142 return useLiveQuery((q) =>
1144 .from({ persons: collection })
1145 .where(({ persons }) => gt(persons.age, 30))
1146 .select(({ persons }) => ({
1147 id: persons.id,
1148 name: persons.name,
1149 }))
1151 })
1152​
1153 // Initially should be true
1154 expect(result.current.isLoading).toBe(true)
1155​
1156 // Start sync manually
1157 act(() => {
1158 collection.preload()
1159 })
1160​
1161 // Trigger the first commit to make collection ready
1162 act(() => {
1163 if (beginFn && commitFn && markReadyFn) {
1164 beginFn()
1165 commitFn()
1166 markReadyFn()
1168 })
1169​
1170 // Insert data
1171 act(() => {
1172 collection.insert({
1173 id: `1`,
1174 name: `John Doe`,
1175 age: 35,
1176 email: `john.doe@example.com`,
1177 isActive: true,
1178 team: `team1`,
1179 })
1180 })
1181​
1182 expect(result.current.isLoading).toBe(false)
1183 expect(result.current.isReady).toBe(true)
1184​
1185 // Wait for collection to become ready
1186 await waitFor(() => {
1187 expect(result.current.isLoading).toBe(false)
1188 })
1189 expect(result.current.status).toBe(`ready`)
1190 })
1191​
1192 it(`should maintain isReady state during live updates`, async () => {
1193 const collection = createCollection(
1194 mockSyncCollectionOptions<Person>({
1195 id: `live-updates-has-loaded-test`,
1196 getKey: (person: Person) => person.id,
1197 initialData: initialPersons,
1198 })
1200​
1201 const { result } = renderHook(() => {
1202 return useLiveQuery((q) =>
1204 .from({ persons: collection })
1205 .where(({ persons }) => gt(persons.age, 30))
1206 .select(({ persons }) => ({
1207 id: persons.id,
1208 name: persons.name,
1209 }))
1211 })
1212​
1213 // Wait for initial load
1214 await waitFor(() => {
1215 expect(result.current.isLoading).toBe(false)
1216 })
1217​
1218 const initialIsReady = result.current.isReady
1219​
1220 // Perform live updates
1221 act(() => {
1222 collection.utils.begin()
1223 collection.utils.write({
1224 type: `insert`,
1225 value: {
1226 id: `4`,
1227 name: `Kyle Doe`,
1228 age: 40,
1229 email: `kyle.doe@example.com`,
1230 isActive: true,
1231 team: `team1`,
1232 },
1233 })
1234 collection.utils.commit()
1235 })
1236​
1237 // Wait for update to process
1238 await waitFor(() => {
1239 expect(result.current.state.size).toBe(2)
1240 })
1241​
1242 // isReady should remain true during live updates
1243 expect(result.current.isReady).toBe(true)
1244 expect(result.current.isReady).toBe(initialIsReady)
1245 })
1246​
1247 it(`should handle isLoading with complex queries including joins`, async () => {
1248 let personBeginFn: (() => void) | undefined
1249 let personCommitFn: (() => void) | undefined
1250 let personMarkReadyFn: (() => void) | undefined
1251 let issueBeginFn: (() => void) | undefined
1252 let issueCommitFn: (() => void) | undefined
1253 let issueMarkReadyFn: (() => void) | undefined
1254​
1255 const personCollection = createCollection<Person>({
1256 id: `join-has-loaded-persons`,
1257 getKey: (person: Person) => person.id,
1258 startSync: false,
1259 sync: {
1260 sync: ({ begin, commit, markReady }) => {
1261 personBeginFn = begin
1262 personCommitFn = commit
1263 personMarkReadyFn = markReady
1264 // Don't sync immediately
1265 },
1266 },
1267 onInsert: async () => {},
1268 onUpdate: async () => {},
1269 onDelete: async () => {},
1270 })
1271​
1272 const issueCollection = createCollection<Issue>({
1273 id: `join-has-loaded-issues`,
1274 getKey: (issue: Issue) => issue.id,
1275 startSync: false,
1276 sync: {
1277 sync: ({ begin, commit, markReady }) => {
1278 issueBeginFn = begin
1279 issueCommitFn = commit
1280 issueMarkReadyFn = markReady
1281 // Don't sync immediately
1282 },
1283 },
1284 onInsert: async () => {},
1285 onUpdate: async () => {},
1286 onDelete: async () => {},
1287 })
1288​
1289 const { result } = renderHook(() => {
1290 return useLiveQuery((q) =>
1292 .from({ issues: issueCollection })
1293 .join({ persons: personCollection }, ({ issues, persons }) =>
1294 eq(issues.userId, persons.id)
1296 .select(({ issues, persons }) => ({
1297 id: issues.id,
1298 title: issues.title,
1299 name: persons.name,
1300 }))
1302 })
1303​
1304 // Initially should be true
1305 expect(result.current.isLoading).toBe(true)
1306​
1307 // Start sync for both collections
1308 act(() => {
1309 personCollection.preload()
1310 issueCollection.preload()
1311 })
1312​
1313 // Trigger the first commit for both collections to make them ready
1314 act(() => {
1315 if (personBeginFn && personCommitFn && personMarkReadyFn) {
1316 personBeginFn()
1317 personCommitFn()
1318 personMarkReadyFn()
1320 if (issueBeginFn && issueCommitFn && issueMarkReadyFn) {
1321 issueBeginFn()
1322 issueCommitFn()
1323 issueMarkReadyFn()
1325 })
1326​
1327 // Insert data into both collections
1328 act(() => {
1329 personCollection.insert({
1330 id: `1`,
1331 name: `John Doe`,
1332 age: 30,
1333 email: `john.doe@example.com`,
1334 isActive: true,
1335 team: `team1`,
1336 })
1337 issueCollection.insert({
1338 id: `1`,
1339 title: `Issue 1`,
1340 description: `Issue 1 description`,
1341 userId: `1`,
1342 })
1343 })
1344​
1345 // Wait for both collections to sync
1346 await waitFor(() => {
1347 expect(result.current.isReady).toBe(true)
1348 })
1349 // Note: Joined data may not appear immediately due to live query evaluation timing
1350 // The main test is that isLoading transitions from false to true
1351 })
1352​
1353 it(`should handle isLoading with parameterized queries`, async () => {
1354 let beginFn: (() => void) | undefined
1355 let commitFn: (() => void) | undefined
1356​
1357 const collection = createCollection<Person>({
1358 id: `params-has-loaded-test`,
1359 getKey: (person: Person) => person.id,
1360 startSync: false,
1361 sync: {
1362 sync: ({ begin, commit, markReady }) => {
1363 beginFn = begin
1364 commitFn = () => {
1365 commit()
1366 markReady()
1368 // Don't sync immediately
1369 },
1370 },
1371 onInsert: async () => {},
1372 onUpdate: async () => {},
1373 onDelete: async () => {},
1374 })
1375​
1376 const { result, rerender } = renderHook(
1377 ({ minAge }: { minAge: number }) => {
1378 return useLiveQuery(
1379 (q) =>
1381 .from({ collection })
1382 .where(({ collection: c }) => gt(c.age, minAge))
1383 .select(({ collection: c }) => ({
1384 id: c.id,
1385 name: c.name,
1386 })),
1387 [minAge]
1389 },
1390 { initialProps: { minAge: 30 } }
1392​
1393 // Initially should be false
1394 expect(result.current.isLoading).toBe(true)
1395​
1396 // Start sync manually
1397 act(() => {
1398 collection.preload()
1399 })
1400​
1401 // Trigger the first commit to make collection ready
1402 act(() => {
1403 if (beginFn && commitFn) {
1404 beginFn()
1405 commitFn()
1407 })
1408​
1409 // Insert data
1410 act(() => {
1411 collection.insert({
1412 id: `1`,
1413 name: `John Doe`,
1414 age: 35,
1415 email: `john.doe@example.com`,
1416 isActive: true,
1417 team: `team1`,
1418 })
1419 collection.insert({
1420 id: `2`,
1421 name: `Jane Doe`,
1422 age: 25,
1423 email: `jane.doe@example.com`,
1424 isActive: true,
1425 team: `team2`,
1426 })
1427 })
1428​
1429 // Wait for initial load
1430 await waitFor(() => {
1431 expect(result.current.isLoading).toBe(false)
1432 })
1433​
1434 // Change parameters
1435 act(() => {
1436 rerender({ minAge: 25 })
1437 })
1438​
1439 // isReady should remain true even when parameters change
1440 await waitFor(() => {
1441 expect(result.current.isReady).toBe(true)
1442 })
1443 // Note: Data size may not change immediately due to live query evaluation timing
1444 // The main test is that isReady remains true when parameters change
1445 })
1446 })