Skip to content
Source
Sign inSign up
TanStack/db

Docs: Add pagination approaches for query collections #1355

ClosedKyleAMathewswants to merge 1 commit intomain fromclaude/pagination-limit-docs-VQMr2opened

Showing 1 changed file with 66 additions and 3 deletions.

x
0 of 1 viewed, 1 left
66 additions and 3 deletionsdocs/collections/query-collection.mdModified
View file
@@ -447,12 +447,31 @@
​
### Example: Large Dataset Pagination
​
+You can use direct writes to append additional pages of data to a collection. However, because query collections treat the `queryFn` result as the [complete state](#full-state-sync), any automatic refetch will replace all directly-written items with whatever `queryFn` returns. To prevent this, you should either disable automatic refetching or design your `queryFn` to merge paginated data.
+​
+#### Approach 1: Direct Writes with Refetch Prevention
+​
+Use direct writes with `staleTime: Infinity` (or `enabled: false`) to prevent the query from refetching and wiping out your paginated data:
+​
```typescript
-// Load additional pages without refetching existing data
-const loadMoreTodos = async (page) => {
+const todosCollection = createCollection(
+ queryCollectionOptions({
+ queryKey: ["todos"],
+ queryFn: async () => {
+ // Initial page load
+ return api.getTodos({ page: 1, limit: 50 })
+ },
+ queryClient,
+ getKey: (item) => item.id,
+ // Prevent automatic refetches from replacing paginated data
+ staleTime: Infinity,
+ })
+)
+​
+// Load additional pages via direct writes
+const loadMoreTodos = async (page: number) => {
const newTodos = await api.getTodos({ page, limit: 50 })