Open History to see the last commit
1import {Link} from '@tanstack/react-router'
2import {
3 GHLink,
4 HighLightComponent,
5 LinkToArticle,
6 OpenAPIRequestsPanelLink,
7} from '/src/components/tutorial'
8
9## Query-driven sync
10
11Sometimes you don't want to load all your data into your collection (e.g. when you have a lot of data), only the subset required by the live queries you're running.
12
13In this demo app, some projects have many more todo items than others. Currently, we load all todo items regardless of which project page the user visits. But what if we could load only items from the currently viewed project?
14
15Well, this is what the `on-demand` sync mode is for.
16
17> FYI: the docs recommend it for large datasets (>50k rows), which means that using it is not really warranted in our case (we have a bit more than 1k rows). <a target="_blank" href="https://tanstack.com/db/latest/docs/overview#sync-modes">(source)</a>
18
19### Switching to `"on-demand"`
20
21Every collection's sync strategy is `"eager"` by default, which loads the entire collection upfront. First, we need to change it to `"on-demand"`:
22
23```ts {4}
24export const todoItemsCollection = createCollection<TodoItemRecord>(
25 queryCollectionOptions({
26 // ...
27 syncMode: "on-demand",
28 // ...
29 })
30```
31
32When the `syncMode` was eager, the function that we used to populate the collection and keep it in sync (`queryFn`) was basically one `fetch` call to the API:
33
34```ts {4-11}
35export const todoItemsCollection = createCollection<TodoItemRecord>(
36 queryCollectionOptions({
37 // ...
38 syncMode: 'eager',
39 queryFn: async () => {
40 // Fetch all the todo items
41 const res = await fetch('/api/todo-items', {method: 'GET'})
42
43 const todoItems: TodoItemRecord[] = await res.json()
44
45 return todoItems
46 },
47 // ...
48 }),
49)
50```
51
52Using this `queryFn` for the `"on-demand"` `syncMode` would defeat the very purpose of it, because it would fetch every single todo item in the database for each query.
53
54Instead, we want the collection to load all the todo items that are required for the queries we run. Right now, we have only one query for the `todoItemsCollection`:
55
56```tsx {5}
57const {data: allTodoItems} = useLiveQuery(
58 (q) =>
59 q
60 .from({todoItem: todoItemsCollection})
61 .where(({todoItem}) => eq(todoItem.projectId, projectId))
62 .orderBy(({todoItem}) => todoItem.position, {
63 direction: 'asc',
64 stringSort: 'lexical',
65 }),
66 [projectId],
67)
68```
69
70The highlighted line in the code block above is the filter we need to use in the database query on the server. Fortunately, when this live query runs, TanStack DB automatically passes all query predicates to the `queryFn`.
71
72```ts {22}
73export const todoItemsCollection = createCollection<TodoItemRecord>(
74 queryCollectionOptions({
75 syncMode: 'on-demand',
76 queryFn: async ({meta}) => {
77 const params = new URLSearchParams()
78
79 if (meta) {
80 const {where} = meta.loadSubsetOptions
81 // Parse the expressions into simple format
82 const parsed = parseLoadSubsetOptions({where})
83 // Build query parameters from parsed filters
84 // Add filters
85 parsed.filters.forEach(({field, operator, value}) => {
86 const fieldName = field.join('.')
87 // Currently only the "eq" operator is supported by our API
88 if (operator === 'eq') {
89 params.set(fieldName, String(value))
90 }
91 })
92 }
93
94 const res = await fetch(`/api/todo-items?${params}`, {method: 'GET'})
95 const todoItems: TodoItemRecord[] = await res.json()
96 return todoItems
97 },
98 }),
99)
100```
101
102Now the `queryFn` will only attempt to fetch the todo items whose projectId matches the one in the live query. You can quickly check it yourself:
103
104- open the <OpenAPIRequestsPanelLink>API Request Panel</OpenAPIRequestsPanelLink>,
105- and [reload this page]()
106
107You should see that the request to `/api/todo-items` has a search string attached to it, similar to this one: `?projectId=aQLI4Nzvmls31l4aep9LqnU`.
108
109The only thing left to do now is to use the project's id from the search params in the API route's handler:
110```ts {6,9-12}
111export default {
112 GET: async ({ request }) => {
113 const url = new URL(request.url);
114
115 // Currently we only support filtering by projectId
116 const projectId = url.searchParams.get("projectId");
117
118 if (projectId) {
119 const results = await db
120 .select()
121 .from(todoItemsTable)
122 .where(eq(todoItemsTable.projectId, projectId));
123 return json(results);
124 } else {
125 const results = await db.select().from(todoItemsTable);
126 return json(results);
127 }
128 },
129}
130```
131
132### Query predicates
133
134In this app, we'll stop here, but the predicates (`where` clauses, `orderBy`, `limit`, and `offset`) coming from the queries can cover far more advanced use cases.
135
136We could use `orderBy` to order elements on the server, `offset` to support pagination, and more.
137
138Check out the <a target="_blank" href="https://tanstack.com/db/latest/docs/collections/query-collection#queryfn-and-predicate-push-down">documentation</a> for more info about them.
139
140### Transitioning from `"eager"` to `"on-demand"`: some pitfalls
141
142When I first refactored `todoItemsCollection` to use `on-demand` sync, I ran into some issues.
143
144#### `.toArrayWhenReady()` vs `.toArray`
145
146For example, this line of code calling the <a target="_blank" href="https://tanstack.com/db/latest/docs/reference/interfaces/Collection#toarraywhenready">`.toArrayWhenReady()` method</a> caused the collection to fetch every single todo item from the remote source:
147
148```ts
149// ❌ Get the current state of the collection from the server
150await todoItemsCollection.toArrayWhenReady()
151```
152
153I had to change it to <a target="_blank" href="https://tanstack.com/db/latest/docs/reference/interfaces/Collection#toarray">`toArray`</a>, to use only existing data in the client-side cache:
154
155```ts
156// ✅ Get the current state of the collection from the cache
157await todoItemsCollection.toArray
158```
159
160#### `.refetch()`
161
162Another line that resulted in loading all the collection data instead of the subset required by the query in `"on-demand"` mode was this one:
163
164```ts
165// ❌ Triggers fetching every todo item in the collection
166todoItemsCollection.utils.refetch();
167```
168
169The key takeaway is that you have to watch out and ensure you don't accidentally sync all the data in the collection when you use `"on-demand"` mode.
170
171### Progressive mode
172
173There is a third sync mode that I haven't previously mentioned called `"progressive"`. Here's how it relates to the other two:
174
175- `"eager"`: load all the data in the collection
176- `"on-demand"`: load only the queried data
177- `"progressive"`: load the queried data first, then everything else in the background
178
179You can read more about the sync modes <a target="_blank" href="https://tanstack.com/db/latest/docs/overview#sync-modes">in the documentation</a>.