Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

query-driven-sync.mdx

179 lines6.7 KB

import {Link} from '@tanstack/react-router' import { GHLink, HighLightComponent, LinkToArticle, OpenAPIRequestsPanelLink, } from '/src/components/tutorial'

Query-driven sync

Sometimes 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.

In 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?

Well, this is what the on-demand sync mode is for.

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). (source)

Switching to "on-demand"

Every collection's sync strategy is "eager" by default, which loads the entire collection upfront. First, we need to change it to "on-demand":

export const todoItemsCollection = createCollection<TodoItemRecord>(
  queryCollectionOptions({
    // ...
    syncMode: "on-demand",
    // ...
  })

When 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:

export const todoItemsCollection = createCollection<TodoItemRecord>(
  queryCollectionOptions({
    // ...
    syncMode: 'eager',
    queryFn: async () => {
      // Fetch all the todo items
      const res = await fetch('/api/todo-items', {method: 'GET'})

      const todoItems: TodoItemRecord[] = await res.json()

      return todoItems
    },
    // ...
  }),
)

Using 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.

Instead, 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:

const {data: allTodoItems} = useLiveQuery(
  (q) =>
    q
      .from({todoItem: todoItemsCollection})
      .where(({todoItem}) => eq(todoItem.projectId, projectId))
      .orderBy(({todoItem}) => todoItem.position, {
        direction: 'asc',
        stringSort: 'lexical',
      }),
  [projectId],
)

The 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.

export const todoItemsCollection = createCollection<TodoItemRecord>(
  queryCollectionOptions({
    syncMode: 'on-demand',
    queryFn: async ({meta}) => {
      const params = new URLSearchParams()

      if (meta) {
        const {where} = meta.loadSubsetOptions
        // Parse the expressions into simple format
        const parsed = parseLoadSubsetOptions({where})
        // Build query parameters from parsed filters
        // Add filters
        parsed.filters.forEach(({field, operator, value}) => {
          const fieldName = field.join('.')
          // Currently only the "eq" operator is supported by our API
          if (operator === 'eq') {
            params.set(fieldName, String(value))
          }
        })
      }

      const res = await fetch(`/api/todo-items?${params}`, {method: 'GET'})
      const todoItems: TodoItemRecord[] = await res.json()
      return todoItems
    },
  }),
)

Now 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:

You should see that the request to /api/todo-items has a search string attached to it, similar to this one: ?projectId=aQLI4Nzvmls31l4aep9LqnU.

The only thing left to do now is to use the project's id from the search params in the API route's handler:

export default {
  GET: async ({ request }) => {
    const url = new URL(request.url);

    // Currently we only support filtering by projectId
    const projectId = url.searchParams.get("projectId");

    if (projectId) {
      const results = await db
        .select()
        .from(todoItemsTable)
        .where(eq(todoItemsTable.projectId, projectId));
      return json(results);
    } else {
      const results = await db.select().from(todoItemsTable);
      return json(results);
    }
  },
}

Query predicates

In 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.

We could use orderBy to order elements on the server, offset to support pagination, and more.

Check out the documentation for more info about them.

Transitioning from "eager" to "on-demand": some pitfalls

When I first refactored todoItemsCollection to use on-demand sync, I ran into some issues.

.toArrayWhenReady() vs .toArray

For example, this line of code calling the .toArrayWhenReady() method caused the collection to fetch every single todo item from the remote source:

// ❌ Get the current state of the collection from the server
await todoItemsCollection.toArrayWhenReady()

I had to change it to toArray, to use only existing data in the client-side cache:

// ✅ Get the current state of the collection from the cache
await todoItemsCollection.toArray

.refetch()

Another line that resulted in loading all the collection data instead of the subset required by the query in "on-demand" mode was this one:

// ❌ Triggers fetching every todo item in the collection
todoItemsCollection.utils.refetch();

The 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.

Progressive mode

There is a third sync mode that I haven't previously mentioned called "progressive". Here's how it relates to the other two:

  • "eager": load all the data in the collection
  • "on-demand": load only the queried data
  • "progressive": load the queried data first, then everything else in the background

You can read more about the sync modes in the documentation.