import {Link} from '@tanstack/react-router' import { GHLink, HighLightComponent, } from '/src/components/tutorial'
How do collections work?#
By default, collections sync with your remote data source when first used in a live query and whenever mutations occur (updates, inserts, deletes, etc.).
When you create a collection, you need to specify how it can sync itself with the server. For simple use cases, this can be accomplished through API calls (managed by TanStack Query), but more advanced scenarios (e.g. two-way sync, multiple clients, etc.) might require sync engines like ElectricSQL.
Our todo app is very simple: there's only one user who can edit the projects, so we can use a good ol' REST API to keep our collections in sync.
Query Collections#
Query Collections are using TanStack Query (you've probably heard of the React library @tanstack/react-query) to sync with your backend.
Check out the definition of the projectsCollection below for an example:
export const projectsCollection = createCollection(
// We use `@tanstack/react-query` to sync the local cache with the remote database
queryCollectionOptions({
queryKey: ['projects'],
// This is the function that loads all the projects
// from the remote database and populates the local cache
queryFn: getProjects,
getKey: (item) => item.id, // Unique identifier for each item
queryClient: TanstackQuery.getContext().queryClient,
// This function tells tanstack-db what to do when
// an item is updated in the collection
onUpdate: async ({transaction}) => {
// [..] Update logic
},
// You can have other keys like `onInsert`, `onDelete`, etc
// for other common data mutations operations
}),
)
What about the backend?#
Using queryCollection-s doesn't place any constraints on your backend. You can use whatever database or language you want!
The only thing queryCollection-s need are API endpoints it can call in the data fetching method (queryFn), and additional endpoints that handle the mutations (onUpdate, onInsert, onDelete, etc).
The projectsCollection's queryFn (getProjects) is basically just a simple fetch request:
async function getProjects() {
const res = await fetch("/api/projects");
if (res.status !== 200) {
throw new Error("Failed to fetch projects");
}
const data: ProjectRecord[] = await res.json();
return data;
}
Uni-directional data flow#
TanStack DB implements a uni-directional data flow, where the source of truth is always the remote data source. Even in the case of mutations (e.g. renaming projects), we see that if mutations fail remotely, the local changes are rolled back automatically.
(This image is from the docs.)
Other syncing strategies#
Sometimes Query Collections are too little or too much for a specific use case. Luckily, there are other ones that can cover these situations:
- `LocalOnly`: For in-memory data
- `LocalStorage`: For data stored in local storage
- `Electric`: For real-time sync using Electric's sync engine
- And more!