Open History to see the last commit
1// The typical app: a TanStack Query collection with an update handler, and a
2// filtered, ordered live query read through the React adapter. Every other
3// scenario adds one feature to this app, so its delta is that feature's cost.
4import { QueryClient } from '@tanstack/query-core'
5import { createCollection, eq } from '@tanstack/db'
6import { queryCollectionOptions } from '@tanstack/query-db-collection'
7import { useLiveQuery } from '@tanstack/react-db'
8
9export const queryClient = new QueryClient()
10
11export const todos = createCollection(
12 queryCollectionOptions({
13 queryKey: [`todos`],
14 queryFn: () => fetch(`/api/todos`).then((response) => response.json()),
15 queryClient,
16 getKey: (todo) => todo.id,
17 onUpdate: async ({ transaction }) => {
18 await fetch(`/api/todos`, {
19 method: `PATCH`,
20 body: JSON.stringify(transaction.mutations.map((m) => m.modified)),
21 })
22 },
23 }),
24)
25
26export function OpenTodos() {
27 const { data } = useLiveQuery((q) =>
28 q
29 .from({ todo: todos })
30 .where(({ todo }) => eq(todo.done, false))
31 .orderBy(({ todo }) => todo.createdAt)
32 .limit(20),
33 )
34 return data
35}