forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLiveQuery.test.tsx
More file actions
2354 lines (2092 loc) · 64.9 KB
/
useLiveQuery.test.tsx
File metadata and controls
2354 lines (2092 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, expect, it } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import {
Query,
count,
createCollection,
createLiveQueryCollection,
createOptimisticAction,
eq,
gt,
lte,
} from '@tanstack/db'
import { useEffect } from 'react'
import { useLiveQuery } from '../src/useLiveQuery'
import { mockSyncCollectionOptions } from '../../db/tests/utils'
type Person = {
id: string
name: string
age: number
email: string
isActive: boolean
team: string
}
type Issue = {
id: string
title: string
description: string
userId: string
}
const initialPersons: Array<Person> = [
{
id: `1`,
name: `John Doe`,
age: 30,
email: `john.doe@example.com`,
isActive: true,
team: `team1`,
},
{
id: `2`,
name: `Jane Doe`,
age: 25,
email: `jane.doe@example.com`,
isActive: true,
team: `team2`,
},
{
id: `3`,
name: `John Smith`,
age: 35,
email: `john.smith@example.com`,
isActive: true,
team: `team1`,
},
]
const initialIssues: Array<Issue> = [
{
id: `1`,
title: `Issue 1`,
description: `Issue 1 description`,
userId: `1`,
},
{
id: `2`,
title: `Issue 2`,
description: `Issue 2 description`,
userId: `2`,
},
{
id: `3`,
title: `Issue 3`,
description: `Issue 3 description`,
userId: `1`,
},
]
describe(`Query Collections`, () => {
it(`should work with basic collection and select`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ persons: collection })
.where(({ persons }) => gt(persons.age, 30))
.select(({ persons }) => ({
id: persons.id,
name: persons.name,
age: persons.age,
})),
)
})
// Wait for collection to sync and state to update
await waitFor(() => {
expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
})
expect(result.current.data).toHaveLength(1)
const johnSmith = result.current.data[0]
expect(johnSmith).toMatchObject({
id: `3`,
name: `John Smith`,
age: 35,
})
})
it(`should keep stable ref`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result, rerender } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ persons: collection })
.where(({ persons }) => gt(persons.age, 30))
.select(({ persons }) => ({
id: persons.id,
name: persons.name,
age: persons.age,
})),
)
})
// Wait for collection to sync and state to update
await waitFor(() => {
expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
})
const data1 = result.current.data
expect(result.current.data).toHaveLength(1)
rerender()
const data2 = result.current.data
// Passes cause the underlying objects are stable
expect(data1).toEqual(data2)
expect(data1[0]).toBe(data2[0])
// Fails cause array isn't
expect(data1).toBe(data2)
})
it(`should be able to return a single row with query builder`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons-2`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ collection })
.where(({ collection: c }) => eq(c.id, `3`))
.findOne(),
)
})
// Wait for collection to sync
await waitFor(() => {
expect(result.current.state.size).toBe(1)
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
expect(result.current.data).toMatchObject({
id: `3`,
name: `John Smith`,
})
})
it(`should be able to return a single row with config object`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons-2`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result } = renderHook(() => {
return useLiveQuery({
query: (q) =>
q
.from({ collection })
.where(({ collection: c }) => eq(c.id, `3`))
.findOne(),
})
})
// Wait for collection to sync
await waitFor(() => {
expect(result.current.state.size).toBe(1)
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
expect(result.current.data).toMatchObject({
id: `3`,
name: `John Smith`,
})
})
it(`should be able to return a single row with collection`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons-2`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const liveQueryCollection = createLiveQueryCollection({
query: (q) =>
q
.from({ collection })
.where(({ collection: c }) => eq(c.id, `3`))
.findOne(),
})
const { result } = renderHook(() => {
return useLiveQuery(liveQueryCollection)
})
// Wait for collection to sync
await waitFor(() => {
expect(result.current.state.size).toBe(1)
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
expect(result.current.data).toMatchObject({
id: `3`,
name: `John Smith`,
})
})
it(`should be able to query a collection with live updates`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `test-persons-2`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ collection })
.where(({ collection: c }) => gt(c.age, 30))
.select(({ collection: c }) => ({
id: c.id,
name: c.name,
}))
.orderBy(({ collection: c }) => c.id, `asc`),
)
})
// Wait for collection to sync
await waitFor(() => {
expect(result.current.state.size).toBe(1)
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
expect(result.current.data.length).toBe(1)
expect(result.current.data[0]).toMatchObject({
id: `3`,
name: `John Smith`,
})
// Insert a new person using the proper utils pattern
act(() => {
collection.utils.begin()
collection.utils.write({
type: `insert`,
value: {
id: `4`,
name: `Kyle Doe`,
age: 40,
email: `kyle.doe@example.com`,
isActive: true,
team: `team1`,
},
})
collection.utils.commit()
})
await waitFor(() => {
expect(result.current.state.size).toBe(2)
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
expect(result.current.state.get(`4`)).toMatchObject({
id: `4`,
name: `Kyle Doe`,
})
expect(result.current.data.length).toBe(2)
expect(result.current.data).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: `3`,
name: `John Smith`,
}),
expect.objectContaining({
id: `4`,
name: `Kyle Doe`,
}),
]),
)
// Update the person
act(() => {
collection.utils.begin()
collection.utils.write({
type: `update`,
value: {
id: `4`,
name: `Kyle Doe 2`,
age: 40,
email: `kyle.doe@example.com`,
isActive: true,
team: `team1`,
},
})
collection.utils.commit()
})
await waitFor(() => {
expect(result.current.state.size).toBe(2)
})
expect(result.current.state.get(`4`)).toMatchObject({
id: `4`,
name: `Kyle Doe 2`,
})
expect(result.current.data.length).toBe(2)
expect(result.current.data).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: `3`,
name: `John Smith`,
}),
expect.objectContaining({
id: `4`,
name: `Kyle Doe 2`,
}),
]),
)
// Delete the person
act(() => {
collection.utils.begin()
collection.utils.write({
type: `delete`,
value: {
id: `4`,
name: `Kyle Doe 2`,
age: 40,
email: `kyle.doe@example.com`,
isActive: true,
team: `team1`,
},
})
collection.utils.commit()
})
await waitFor(() => {
expect(result.current.state.size).toBe(1)
})
expect(result.current.state.get(`4`)).toBeUndefined()
expect(result.current.data.length).toBe(1)
expect(result.current.data[0]).toMatchObject({
id: `3`,
name: `John Smith`,
})
})
it(`should join collections and return combined results with live updates`, async () => {
// Create person collection
const personCollection = createCollection(
mockSyncCollectionOptions<Person>({
id: `person-collection-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
// Create issue collection
const issueCollection = createCollection(
mockSyncCollectionOptions<Issue>({
id: `issue-collection-test`,
getKey: (issue: Issue) => issue.id,
initialData: initialIssues,
}),
)
const { result } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ issues: issueCollection })
.join({ persons: personCollection }, ({ issues, persons }) =>
eq(issues.userId, persons.id),
)
.select(({ issues, persons }) => ({
id: issues.id,
title: issues.title,
name: persons?.name,
})),
)
})
// Wait for collections to sync
await waitFor(() => {
expect(result.current.state.size).toBe(3)
})
// Verify that we have the expected joined results
expect(result.current.state.get(`[1,1]`)).toMatchObject({
id: `1`,
name: `John Doe`,
title: `Issue 1`,
})
expect(result.current.state.get(`[2,2]`)).toMatchObject({
id: `2`,
name: `Jane Doe`,
title: `Issue 2`,
})
expect(result.current.state.get(`[3,1]`)).toMatchObject({
id: `3`,
name: `John Doe`,
title: `Issue 3`,
})
// Add a new issue for user 2
act(() => {
issueCollection.utils.begin()
issueCollection.utils.write({
type: `insert`,
value: {
id: `4`,
title: `Issue 4`,
description: `Issue 4 description`,
userId: `2`,
},
})
issueCollection.utils.commit()
})
await waitFor(() => {
expect(result.current.state.size).toBe(4)
})
expect(result.current.state.get(`[4,2]`)).toMatchObject({
id: `4`,
name: `Jane Doe`,
title: `Issue 4`,
})
// Update an issue we're already joined with
act(() => {
issueCollection.utils.begin()
issueCollection.utils.write({
type: `update`,
value: {
id: `2`,
title: `Updated Issue 2`,
description: `Issue 2 description`,
userId: `2`,
},
})
issueCollection.utils.commit()
})
await waitFor(() => {
// The updated title should be reflected in the joined results
expect(result.current.state.get(`[2,2]`)).toMatchObject({
id: `2`,
name: `Jane Doe`,
title: `Updated Issue 2`,
})
})
// Delete an issue
act(() => {
issueCollection.utils.begin()
issueCollection.utils.write({
type: `delete`,
value: {
id: `3`,
title: `Issue 3`,
description: `Issue 3 description`,
userId: `1`,
},
})
issueCollection.utils.commit()
})
await new Promise((resolve) => setTimeout(resolve, 10))
// After deletion, issue 3 should no longer have a joined result
expect(result.current.state.get(`[3,1]`)).toBeUndefined()
expect(result.current.state.size).toBe(3)
})
it(`should recompile query when parameters change and change results`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `params-change-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result, rerender } = renderHook(
({ minAge }: { minAge: number }) => {
return useLiveQuery(
(q) =>
q
.from({ collection })
.where(({ collection: c }) => gt(c.age, minAge))
.select(({ collection: c }) => ({
id: c.id,
name: c.name,
age: c.age,
})),
[minAge],
)
},
{ initialProps: { minAge: 30 } },
)
// Wait for collection to sync
await new Promise((resolve) => setTimeout(resolve, 10))
// Initially should return only people older than 30
expect(result.current.state.size).toBe(1)
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
age: 35,
})
// Change the parameter to include more people
act(() => {
rerender({ minAge: 20 })
})
await new Promise((resolve) => setTimeout(resolve, 10))
// Now should return all people as they're all older than 20
expect(result.current.state.size).toBe(3)
expect(result.current.state.get(`1`)).toMatchObject({
id: `1`,
name: `John Doe`,
age: 30,
})
expect(result.current.state.get(`2`)).toMatchObject({
id: `2`,
name: `Jane Doe`,
age: 25,
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
age: 35,
})
// Change to exclude everyone
act(() => {
rerender({ minAge: 50 })
})
await new Promise((resolve) => setTimeout(resolve, 10))
// Should now be empty
expect(result.current.state.size).toBe(0)
})
it(`should stop old query when parameters change`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `stop-query-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const { result, rerender } = renderHook(
({ minAge }: { minAge: number }) => {
return useLiveQuery(
(q) =>
q
.from({ collection })
.where(({ collection: c }) => gt(c.age, minAge))
.select(({ collection: c }) => ({
id: c.id,
name: c.name,
})),
[minAge],
)
},
{ initialProps: { minAge: 30 } },
)
// Wait for collection to sync
await new Promise((resolve) => setTimeout(resolve, 10))
// Initial query should return only people older than 30
expect(result.current.state.size).toBe(1)
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
// Change the parameter to include more people
act(() => {
rerender({ minAge: 25 })
})
await new Promise((resolve) => setTimeout(resolve, 10))
// Query should now return all people older than 25
expect(result.current.state.size).toBe(2)
expect(result.current.state.get(`1`)).toMatchObject({
id: `1`,
name: `John Doe`,
})
expect(result.current.state.get(`3`)).toMatchObject({
id: `3`,
name: `John Smith`,
})
// Change to a value that excludes everyone
act(() => {
rerender({ minAge: 50 })
})
await new Promise((resolve) => setTimeout(resolve, 10))
// Should now be empty
expect(result.current.state.size).toBe(0)
})
it(`should be able to query a result collection with live updates`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `optimistic-changes-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
// Initial query
const { result } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ collection })
.where(({ collection: c }) => gt(c.age, 30))
.select(({ collection: c }) => ({
id: c.id,
name: c.name,
team: c.team,
}))
.orderBy(({ collection: c }) => c.id, `asc`),
)
})
// Wait for collection to sync
await new Promise((resolve) => setTimeout(resolve, 10))
// Grouped query derived from initial query
const { result: groupedResult } = renderHook(() => {
return useLiveQuery((q) =>
q
.from({ queryResult: result.current.collection })
.groupBy(({ queryResult }) => queryResult.team)
.select(({ queryResult }) => ({
team: queryResult.team,
count: count(queryResult.id),
})),
)
})
// Wait for grouped query to sync
await new Promise((resolve) => setTimeout(resolve, 10))
// Verify initial grouped results
expect(groupedResult.current.state.size).toBe(1)
const teamResult = Array.from(groupedResult.current.state.values())[0]
expect(teamResult).toMatchObject({
team: `team1`,
count: 1,
})
// Insert two new users in different teams
act(() => {
collection.utils.begin()
collection.utils.write({
type: `insert`,
value: {
id: `5`,
name: `Sarah Jones`,
age: 32,
email: `sarah.jones@example.com`,
isActive: true,
team: `team1`,
},
})
collection.utils.write({
type: `insert`,
value: {
id: `6`,
name: `Mike Wilson`,
age: 38,
email: `mike.wilson@example.com`,
isActive: true,
team: `team2`,
},
})
collection.utils.commit()
})
await new Promise((resolve) => setTimeout(resolve, 10))
// Verify the grouped results include the new team members
expect(groupedResult.current.state.size).toBe(2)
const groupedResults = Array.from(groupedResult.current.state.values())
const team1Result = groupedResults.find((r) => r.team === `team1`)
const team2Result = groupedResults.find((r) => r.team === `team2`)
expect(team1Result).toMatchObject({
team: `team1`,
count: 2, // John Smith + Sarah Jones
})
expect(team2Result).toMatchObject({
team: `team2`,
count: 1, // Mike Wilson
})
})
it(`optimistic state is dropped after commit`, async () => {
// Track renders and states
const renderStates: Array<{
stateSize: number
hasTempKey: boolean
hasPermKey: boolean
timestamp: number
}> = []
// Create person collection
const personCollection = createCollection(
mockSyncCollectionOptions<Person>({
id: `person-collection-test-bug`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
// Create issue collection
const issueCollection = createCollection(
mockSyncCollectionOptions<Issue>({
id: `issue-collection-test-bug`,
getKey: (issue: Issue) => issue.id,
initialData: initialIssues,
}),
)
// Render the hook with a query that joins persons and issues
const { result } = renderHook(() => {
const queryResult = useLiveQuery((q) =>
q
.from({ issues: issueCollection })
.join({ persons: personCollection }, ({ issues, persons }) =>
eq(issues.userId, persons.id),
)
.select(({ issues, persons }) => ({
id: issues.id,
title: issues.title,
name: persons?.name,
})),
)
// Track each render state
useEffect(() => {
renderStates.push({
stateSize: queryResult.state.size,
hasTempKey: queryResult.state.has(`[temp-key,1]`),
hasPermKey: queryResult.state.has(`[4,1]`),
timestamp: Date.now(),
})
}, [queryResult.state])
return queryResult
})
// Wait for collections to sync and verify initial state
await waitFor(() => {
expect(result.current.state.size).toBe(3)
})
// Reset render states array for clarity in the remaining test
renderStates.length = 0
// Create an optimistic action for adding issues
type AddIssueInput = {
title: string
description: string
userId: string
}
const addIssue = createOptimisticAction<AddIssueInput>({
onMutate: (issueInput) => {
// Optimistically insert with temporary key
issueCollection.insert({
id: `temp-key`,
title: issueInput.title,
description: issueInput.description,
userId: issueInput.userId,
})
},
mutationFn: async (issueInput) => {
// Simulate server persistence - in a real app, this would be an API call
await new Promise((resolve) => setTimeout(resolve, 10)) // Simulate network delay
// After "server" responds, update the collection with permanent ID using utils
// Note: This act() is inside the mutationFn and handles the async server response
act(() => {
issueCollection.utils.begin()
issueCollection.utils.write({
type: `delete`,
value: {
id: `temp-key`,
title: issueInput.title,
description: issueInput.description,
userId: issueInput.userId,
},
})
issueCollection.utils.write({
type: `insert`,
value: {
id: `4`, // Use the permanent ID
title: issueInput.title,
description: issueInput.description,
userId: issueInput.userId,
},
})
issueCollection.utils.commit()
})
return { success: true, id: `4` }
},
})
// Perform optimistic insert of a new issue
let transaction: any
act(() => {
transaction = addIssue({
title: `New Issue`,
description: `New Issue Description`,
userId: `1`,
})
})
await waitFor(() => {
// Verify optimistic state is immediately reflected
expect(result.current.state.size).toBe(4)
expect(result.current.state.get(`[temp-key,1]`)).toMatchObject({
id: `temp-key`,
name: `John Doe`,
title: `New Issue`,
})
expect(result.current.state.get(`[4,1]`)).toBeUndefined()
})
// Wait for the transaction to be committed
await transaction.isPersisted.promise
await waitFor(() => {
// Wait for the permanent key to appear
expect(result.current.state.get(`[4,1]`)).toBeDefined()
})
// Check if we had any render where the temp key was removed but the permanent key wasn't added yet
const hadFlicker = renderStates.some(
(state) =>
!state.hasTempKey && !state.hasPermKey && state.stateSize === 3,
)
expect(hadFlicker).toBe(false)
// Verify the temporary key is replaced by the permanent one
expect(result.current.state.size).toBe(4)
expect(result.current.state.get(`[temp-key,1]`)).toBeUndefined()
expect(result.current.state.get(`[4,1]`)).toMatchObject({
id: `4`,
name: `John Doe`,
title: `New Issue`,
})
})
it(`should accept pre-created live query collection`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Person>({
id: `pre-created-collection-test`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
// Create a live query collection beforehand
const liveQueryCollection = createLiveQueryCollection({
query: (q) =>
q
.from({ persons: collection })
.where(({ persons }) => gt(persons.age, 30))
.select(({ persons }) => ({
id: persons.id,
name: persons.name,
age: persons.age,
})),
startSync: true,
})
const { result } = renderHook(() => {
return useLiveQuery(liveQueryCollection)
})
// Wait for collection to sync and state to update
await waitFor(() => {
expect(result.current.state.size).toBe(1) // Only John Smith (age 35)
})
expect(result.current.data).toHaveLength(1)
const johnSmith = result.current.data[0]
expect(johnSmith).toMatchObject({
id: `3`,
name: `John Smith`,
age: 35,
})
// Verify that the returned collection is the same instance
expect(result.current.collection).toBe(liveQueryCollection)
})
it(`should switch to a different pre-created live query collection when changed`, async () => {
const collection1 = createCollection(
mockSyncCollectionOptions<Person>({
id: `collection-1`,
getKey: (person: Person) => person.id,
initialData: initialPersons,
}),
)
const collection2 = createCollection(
mockSyncCollectionOptions<Person>({
id: `collection-2`,
getKey: (person: Person) => person.id,
initialData: [
{
id: `4`,
name: `Alice Cooper`,