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

useLiveQuery.test.tsx

1,364 lines37.1 KB

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