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({
25 query: (q) =>
26 q
27 .from({ todo: queryTodoCollection })
28 .orderBy(({ todo }) => todo.created_at, `asc`),
29 })
30
31 const { data: configData } = useLiveQuery({
32 query: (q) => q.from({ config: queryConfigCollection }),
33 })
34
35 // Query collections automatically refetch after handler completes
36 const configMutationFn = async ({
37 transaction,
38 }: {
39 transaction: Transaction
40 }) => {
41 // Handle inserts
42 const inserts = transaction.mutations.filter((m) => m.type === `insert`)
43 await Promise.all(
44 inserts.map(async (mutation) => {
45 await api.config.create(mutation.modified)
46 }),
47 )
48
49 // Handle updates
50 const updates = transaction.mutations.filter((m) => m.type === `update`)
51 await Promise.all(
52 updates.map(async (mutation) => {
53 if (!(`id` in mutation.original)) {
54 throw new Error(`Original config not found for update`)
55 }
56 await api.config.update(mutation.original.id, mutation.changes)
57 }),
58 )
59
60 // Trigger refetch to get confirmed server state
61 await queryConfigCollection.utils.refetch()
62 }
63
64 return (
65 <TodoApp
66 todos={todos}
67 configData={configData}
68 todoCollection={queryTodoCollection}
69 configCollection={queryConfigCollection}
70 title="todos (query)"
71 configMutationFn={configMutationFn}
72 />
73 )
74}