Open History to see the last commit
1import * as React from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useLiveQuery } from '@tanstack/react-db'
4import { queryConfigCollection, queryTodoCollection } from '../lib/collections'
5import { TodoApp } from '../components/TodoApp'
6import { api } from '../lib/api'
7import type { Transaction } from '@tanstack/react-db'
8
9export const Route = createFileRoute(`/query`)({
10 component: QueryPage,
11 ssr: false,
12 loader: async () => {
13 await Promise.all([
14 queryTodoCollection.preload(),
15 queryConfigCollection.preload(),
16 ])
17
18 return null
19 },
20})
21
22function QueryPage() {
23 // Get data using live queries with Query collections
24 const { data: todos } = useLiveQuery((q) =>
25 q
26 .from({ todo: queryTodoCollection })
27 .orderBy(({ todo }) => todo.created_at, `asc`),
28 )
29
30 const { data: configData } = useLiveQuery((q) =>
31 q.from({ config: queryConfigCollection }),
32 )
33
34 // Query collections automatically refetch after handler completes
35 const configMutationFn = async ({
36 transaction,
37 }: {
38 transaction: Transaction
39 }) => {
40 // Handle inserts
41 const inserts = transaction.mutations.filter((m) => m.type === `insert`)
42 await Promise.all(
43 inserts.map(async (mutation) => {
44 await api.config.create(mutation.modified)
45 }),
46 )
47
48 // Handle updates
49 const updates = transaction.mutations.filter((m) => m.type === `update`)
50 await Promise.all(
51 updates.map(async (mutation) => {
52 if (!(`id` in mutation.original)) {
53 throw new Error(`Original config not found for update`)
54 }
55 await api.config.update(mutation.original.id, mutation.changes)
56 }),
57 )
58
59 // Trigger refetch to get confirmed server state
60 await queryConfigCollection.utils.refetch()
61 }
62
63 return (
64 <TodoApp
65 todos={todos}
66 configData={configData}
67 todoCollection={queryTodoCollection}
68 configCollection={queryConfigCollection}
69 title="todos (query)"
70 configMutationFn={configMutationFn}
71 />
72 )
73}