forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLiveInfiniteQuery.test.tsx
More file actions
1871 lines (1595 loc) · 53.4 KB
/
useLiveInfiniteQuery.test.tsx
File metadata and controls
1871 lines (1595 loc) · 53.4 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 { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
import { mockSyncCollectionOptions } from '../../db/tests/utils'
import { createFilterFunctionFromExpression } from '../../db/src/collection/change-events'
import type { LoadSubsetOptions } from '@tanstack/db'
type Post = {
id: string
title: string
content: string
createdAt: number
category: string
}
function createMockPosts(count: number): Array<Post> {
const posts: Array<Post> = []
for (let i = 1; i <= count; i++) {
posts.push({
id: `${i}`,
title: `Post ${i}`,
content: `Content ${i}`,
createdAt: 1000000 - i * 1000, // Descending order
category: i % 2 === 0 ? `tech` : `life`,
})
}
return posts
}
type OnDemandCollectionOptions = {
id: string
allPosts: Array<Post>
autoIndex?: `off` | `eager`
asyncDelay?: number
}
/**
* Creates an on-demand collection with a loadSubset handler that supports
* sorting, cursor-based pagination, and limit. Returns the collection and
* a reference to recorded loadSubset calls for test assertions.
*/
function createOnDemandCollection(opts: OnDemandCollectionOptions) {
const loadSubsetCalls: Array<LoadSubsetOptions> = []
const { id, allPosts, autoIndex, asyncDelay } = opts
const collection = createCollection<Post>({
id,
getKey: (post: Post) => post.id,
syncMode: `on-demand`,
startSync: true,
...(autoIndex ? { autoIndex } : {}),
sync: {
sync: ({ markReady, begin, write, commit }) => {
markReady()
return {
loadSubset: (subsetOpts: LoadSubsetOptions) => {
loadSubsetCalls.push({ ...subsetOpts })
let filtered = [...allPosts].sort(
(a, b) => b.createdAt - a.createdAt,
)
if (subsetOpts.cursor) {
const whereFromFn = createFilterFunctionFromExpression(
subsetOpts.cursor.whereFrom,
)
filtered = filtered.filter(whereFromFn)
}
if (subsetOpts.limit !== undefined) {
filtered = filtered.slice(0, subsetOpts.limit)
}
function writeAll(): void {
begin()
for (const post of filtered) {
write({ type: `insert`, value: post })
}
commit()
}
if (asyncDelay !== undefined) {
return new Promise<void>((resolve) => {
setTimeout(() => {
writeAll()
resolve()
}, asyncDelay)
})
}
writeAll()
return true
},
}
},
},
})
return { collection, loadSubsetCalls }
}
describe(`useLiveInfiniteQuery`, () => {
it(`should fetch initial page of data`, async () => {
const posts = createMockPosts(50)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `initial-page-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`)
.select(({ posts: p }) => ({
id: p.id,
title: p.title,
createdAt: p.createdAt,
})),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Should have 1 page initially
expect(result.current.pages).toHaveLength(1)
expect(result.current.pages[0]).toHaveLength(10)
// Data should be flattened
expect(result.current.data).toHaveLength(10)
// Should have next page since we have 50 items total
expect(result.current.hasNextPage).toBe(true)
// First item should be Post 1 (most recent by createdAt)
expect(result.current.pages[0]![0]).toMatchObject({
id: `1`,
title: `Post 1`,
})
})
it(`should fetch multiple pages`, async () => {
const posts = createMockPosts(50)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `multiple-pages-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Initially 1 page
expect(result.current.pages).toHaveLength(1)
expect(result.current.hasNextPage).toBe(true)
// Fetch next page
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
expect(result.current.pages[0]).toHaveLength(10)
expect(result.current.pages[1]).toHaveLength(10)
expect(result.current.data).toHaveLength(20)
expect(result.current.hasNextPage).toBe(true)
// Fetch another page
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(3)
})
expect(result.current.data).toHaveLength(30)
expect(result.current.hasNextPage).toBe(true)
})
it(`should detect when no more pages available`, async () => {
const posts = createMockPosts(25)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `no-more-pages-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Page 1: 10 items, has more
expect(result.current.pages).toHaveLength(1)
expect(result.current.hasNextPage).toBe(true)
// Fetch page 2
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
// Page 2: 10 items, has more
expect(result.current.pages[1]).toHaveLength(10)
expect(result.current.hasNextPage).toBe(true)
// Fetch page 3
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(3)
})
// Page 3: 5 items, no more
expect(result.current.pages[2]).toHaveLength(5)
expect(result.current.data).toHaveLength(25)
expect(result.current.hasNextPage).toBe(false)
})
it(`should handle empty results`, async () => {
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `empty-results-test`,
getKey: (post: Post) => post.id,
initialData: [],
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// With no data, we still have 1 page (which is empty)
expect(result.current.pages).toHaveLength(1)
expect(result.current.pages[0]).toHaveLength(0)
expect(result.current.data).toHaveLength(0)
expect(result.current.hasNextPage).toBe(false)
})
it(`should update pages when underlying data changes`, async () => {
const posts = createMockPosts(30)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `live-updates-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Fetch 2 pages
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
expect(result.current.data).toHaveLength(20)
// Insert a new post with most recent timestamp
act(() => {
collection.utils.begin()
collection.utils.write({
type: `insert`,
value: {
id: `new-1`,
title: `New Post`,
content: `New Content`,
createdAt: 1000001, // Most recent
category: `tech`,
},
})
collection.utils.commit()
})
await waitFor(() => {
// New post should be first
expect(result.current.pages[0]![0]).toMatchObject({
id: `new-1`,
title: `New Post`,
})
})
// Still showing 2 pages (20 items), but content has shifted
// The new item is included, pushing the last item out of view
expect(result.current.pages).toHaveLength(2)
expect(result.current.data).toHaveLength(20)
expect(result.current.pages[0]).toHaveLength(10)
expect(result.current.pages[1]).toHaveLength(10)
})
it(`should handle deletions across pages`, async () => {
const posts = createMockPosts(25)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `deletions-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Fetch 2 pages
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
expect(result.current.data).toHaveLength(20)
const firstItemId = result.current.data[0]!.id
// Delete the first item
act(() => {
collection.utils.begin()
collection.utils.write({
type: `delete`,
value: posts[0]!,
})
collection.utils.commit()
})
await waitFor(() => {
// First item should have changed
expect(result.current.data[0]!.id).not.toBe(firstItemId)
})
// Still showing 2 pages, each pulls from remaining 24 items
// Page 1: items 0-9 (10 items)
// Page 2: items 10-19 (10 items)
// Total: 20 items (item 20-23 are beyond our loaded pages)
expect(result.current.pages).toHaveLength(2)
expect(result.current.data).toHaveLength(20)
expect(result.current.pages[0]).toHaveLength(10)
expect(result.current.pages[1]).toHaveLength(10)
})
it(`should handle deletion from partial page with descending order`, async () => {
// Create only 5 items - fewer than the pageSize of 20
const posts = createMockPosts(5)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `partial-page-deletion-desc-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 20,
getNextPageParam: (lastPage) =>
lastPage.length === 20 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Should have all 5 items on one page (partial page)
expect(result.current.pages).toHaveLength(1)
expect(result.current.data).toHaveLength(5)
expect(result.current.hasNextPage).toBe(false)
// Verify the first item (most recent by createdAt descending)
const firstItemId = result.current.data[0]!.id
expect(firstItemId).toBe(`1`) // Post 1 has the highest createdAt
// Delete the first item (the one that appears first in descending order)
act(() => {
collection.utils.begin()
collection.utils.write({
type: `delete`,
value: posts[0]!, // Post 1
})
collection.utils.commit()
})
// The deleted item should disappear from the result
await waitFor(() => {
expect(result.current.data).toHaveLength(4)
})
// Verify the deleted item is no longer in the data
expect(
result.current.data.find((p) => p.id === firstItemId),
).toBeUndefined()
// Verify the new first item is Post 2
expect(result.current.data[0]!.id).toBe(`2`)
// Still should have 1 page with 4 items
expect(result.current.pages).toHaveLength(1)
expect(result.current.pages[0]).toHaveLength(4)
expect(result.current.hasNextPage).toBe(false)
})
it(`should handle deletion from partial page with ascending order`, async () => {
// Create only 5 items - fewer than the pageSize of 20
const posts = createMockPosts(5)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `partial-page-deletion-asc-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `asc`), // ascending order
{
pageSize: 20,
getNextPageParam: (lastPage) =>
lastPage.length === 20 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Should have all 5 items on one page (partial page)
expect(result.current.pages).toHaveLength(1)
expect(result.current.data).toHaveLength(5)
expect(result.current.hasNextPage).toBe(false)
// In ascending order, Post 5 has the lowest createdAt and appears first
const firstItemId = result.current.data[0]!.id
expect(firstItemId).toBe(`5`) // Post 5 has the lowest createdAt
// Delete the first item (the one that appears first in ascending order)
act(() => {
collection.utils.begin()
collection.utils.write({
type: `delete`,
value: posts[4]!, // Post 5 (index 4 in array)
})
collection.utils.commit()
})
// The deleted item should disappear from the result
await waitFor(() => {
expect(result.current.data).toHaveLength(4)
})
// Verify the deleted item is no longer in the data
expect(
result.current.data.find((p) => p.id === firstItemId),
).toBeUndefined()
// Still should have 1 page with 4 items
expect(result.current.pages).toHaveLength(1)
expect(result.current.pages[0]).toHaveLength(4)
expect(result.current.hasNextPage).toBe(false)
})
it(`should work with where clauses`, async () => {
const posts = createMockPosts(50)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `where-clause-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.where(({ posts: p }) => eq(p.category, `tech`))
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 5,
getNextPageParam: (lastPage) =>
lastPage.length === 5 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Should only have tech posts (every even ID)
expect(result.current.pages).toHaveLength(1)
expect(result.current.pages[0]).toHaveLength(5)
// All items should be tech category
result.current.pages[0]!.forEach((post) => {
expect(post.category).toBe(`tech`)
})
// Should have more pages
expect(result.current.hasNextPage).toBe(true)
// Fetch next page
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
expect(result.current.data).toHaveLength(10)
})
it(`should re-execute query when dependencies change`, async () => {
const posts = createMockPosts(50)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `deps-change-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result, rerender } = renderHook(
({ category }: { category: string }) => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.where(({ posts: p }) => eq(p.category, category))
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 5,
getNextPageParam: (lastPage) =>
lastPage.length === 5 ? lastPage.length : undefined,
},
[category],
)
},
{ initialProps: { category: `tech` } },
)
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Fetch 2 pages of tech posts
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
// Change category to life
act(() => {
rerender({ category: `life` })
})
await waitFor(() => {
// Should reset to 1 page with life posts
expect(result.current.pages).toHaveLength(1)
})
// All items should be life category
result.current.pages[0]!.forEach((post) => {
expect(post.category).toBe(`life`)
})
})
it(`should track pageParams correctly`, async () => {
const posts = createMockPosts(30)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `page-params-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
initialPageParam: 0,
getNextPageParam: (lastPage, _allPages, lastPageParam) =>
lastPage.length === 10 ? lastPageParam + 1 : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
expect(result.current.pageParams).toEqual([0])
// Fetch next page
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pageParams).toEqual([0, 1])
})
// Fetch another page
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pageParams).toEqual([0, 1, 2])
})
})
it(`should handle exact page size boundaries`, async () => {
const posts = createMockPosts(20) // Exactly 2 pages
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `exact-boundary-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
// Better getNextPageParam that checks against total data available
getNextPageParam: (lastPage, allPages) => {
// If last page is not full, we're done
if (lastPage.length < 10) return undefined
// Check if we've likely loaded all data (this is a heuristic)
// In a real app with backend, you'd check response metadata
const totalLoaded = allPages.flat().length
// If we have less than a full page left, no more pages
return totalLoaded
},
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
expect(result.current.hasNextPage).toBe(true)
// Fetch page 2
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
expect(result.current.pages[1]).toHaveLength(10)
// With setWindow peek-ahead, we can now detect no more pages immediately
// We request 21 items (2 * 10 + 1 peek) but only get 20, so we know there's no more
expect(result.current.hasNextPage).toBe(false)
// Verify total data
expect(result.current.data).toHaveLength(20)
})
it(`should not fetch when already fetching`, async () => {
const posts = createMockPosts(50)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `concurrent-fetch-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
expect(result.current.pages).toHaveLength(1)
// With sync data, all fetches complete immediately, so all 3 calls will succeed
// The key is that they won't cause race conditions or errors
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(3)
})
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(4)
})
// All fetches should have succeeded
expect(result.current.pages).toHaveLength(4)
expect(result.current.data).toHaveLength(40)
})
it(`should not fetch when hasNextPage is false`, async () => {
const posts = createMockPosts(5)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `no-fetch-when-done-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
expect(result.current.hasNextPage).toBe(false)
expect(result.current.pages).toHaveLength(1)
// Try to fetch when there's no next page
act(() => {
result.current.fetchNextPage()
})
await new Promise((resolve) => setTimeout(resolve, 50))
// Should still have only 1 page
expect(result.current.pages).toHaveLength(1)
})
it(`should support custom initialPageParam`, async () => {
const posts = createMockPosts(30)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `initial-param-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
initialPageParam: 100,
getNextPageParam: (lastPage, _allPages, lastPageParam) =>
lastPage.length === 10 ? lastPageParam + 1 : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
expect(result.current.pageParams).toEqual([100])
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pageParams).toEqual([100, 101])
})
})
it(`should detect hasNextPage change when new items are synced`, async () => {
// Start with exactly 20 items (2 pages)
const posts = createMockPosts(20)
const collection = createCollection(
mockSyncCollectionOptions<Post>({
id: `sync-detection-test`,
getKey: (post: Post) => post.id,
initialData: posts,
}),
)
const { result } = renderHook(() => {
return useLiveInfiniteQuery(
(q) =>
q
.from({ posts: collection })
.orderBy(({ posts: p }) => p.createdAt, `desc`),
{
pageSize: 10,
getNextPageParam: (lastPage) =>
lastPage.length === 10 ? lastPage.length : undefined,
},
)
})
await waitFor(() => {
expect(result.current.isReady).toBe(true)
})
// Load both pages
act(() => {
result.current.fetchNextPage()
})
await waitFor(() => {
expect(result.current.pages).toHaveLength(2)
})
// Should have no next page (exactly 20 items, 2 full pages, peek returns nothing)
expect(result.current.hasNextPage).toBe(false)
expect(result.current.data).toHaveLength(20)
// Add 5 more items to the collection
act(() => {
collection.utils.begin()
for (let i = 0; i < 5; i++) {
collection.utils.write({
type: `insert`,
value: {
id: `new-${i}`,
title: `New Post ${i}`,
content: `Content ${i}`,
createdAt: Date.now() + i,
category: `tech`,
},
})
}
collection.utils.commit()
})
// Should now detect that there's a next page available
await waitFor(() => {
expect(result.current.hasNextPage).toBe(true)
})
// Data should still be 20 items (we haven't fetched the next page yet)