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

collections-intro.mdx

69 lines3.3 KB

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

What are collections?

A quick demo

We have a projects table in our database. If you click the button below, you can see all the components that to display data from this table:

Highlight components

In a traditional React app, both of them would probably fetch the data they need from the server, managing their own cache. If you update something somewhere (e.g. rename a project), you need to manually update the cache, and after a while even knowing what to update becomes a challenge.

TanStack DB provides you with a new option. You can store the projects' data in a collection, and use it as a single source of truth everywhere.

In the AppSidebar component, we use this query to get the list of projects:

  const { data: projects } = useLiveQuery((q) =>
    q.from({
      project: projectsCollection,
    }),
  );
Highlight `AppSidebar`

On the project's page, the RouteComponent loads only the data relevant for the currently viewed project:

  const {
    data: [project],
  } = useLiveQuery(
    (q) =>
      q
        .from({ project: projectsCollection })
        .where(({ project }) => eq(project.id, projectId)),
    // This hook has a dependency array as seen below.
    // Every time the `projectId` changes (i.e. we navigate
    // to a new page), the query is executed again
    [projectId],
  );
Highlight `RouteComponent`

"So many queries... Isn't that ...slow?"

Thankfully, no, and there are two reasons why.

  1. Multiple queries using the same collection will sync the collection with the backend only once, and use the cache the rest of the times.

    • To check it, follow these steps:

      1. go to the Network tab in your browser's dev tools
      2. reload the page (click here)
      3. see that there is only one GET request to the /api/projects endpoint, despite having 2 components using data from the projectCollection
      4. if you navigate to any other project page, you shouldn't see more requests made

      Unless the cache needs to be revalidated (because the state has been mutated or went stale).

  2. Live queries updated incrementally, (they use d2ts, a differential dataflow library)

    • this results in sub-millisecond execution times (even for complex queries)
    • which means that it's BLAZING FAST!!! ⚡⚡⚡

Querying multiple collections

Yes, you can even use innerJoin() and other join operations to query multiple collections. This demo doesn't have an example for that yet, but you can check the documentation if you're interested.