import {Link} from '@tanstack/react-router' import { GHLink, HighLightComponent, } from '/src/components/tutorial'
How do collections work?#
By default, collections are synced with the remote source when they are first used in a live query, and every time a mutation occurs (update, insert, delete, etc).
For most use cases, collections live on the front end. They don't know how to fetch or update remote data on their own, so you need to use a sync engine that handles that part.
Query Collections#
Query Collections are using TanStack Query (you've probably heard of at least the React lib @tanstack/react-query) to sync with your backend.
It's important to note that collections are part of your front-end code. They don't know how to receive or send data to the server themselves, you need a sync engine for that.
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 db
queryCollectionOptions({
queryKey: ['projects'],
// This is the function that loads all the projects
// from the remote db and populates the local cache
queryFn: getProjects,
getKey: (item) => item.id,
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 endpoint 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've seen that if the mutation failed remotely, the local changes were rolled back automatically.
(This image is from the docs.)
Other sync engines#
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`: data stored in local storage
- `Electric`: real-time sync using Electric's sync engine
- and more!