Open History to see the last commit
1import { createCollection, parseLoadSubsetOptions } from "@tanstack/db";
2import { queryCollectionOptions } from "@tanstack/query-db-collection";
3import { toast } from "sonner";
4import type { TodoItemRecord } from "@/db/schema";
5import * as TanstackQuery from "@/integrations/tanstack-query/root-provider";
6import type { TodoItemCreateDataType } from "@/local-api/api.todo-items";
7
8async function updateTodoItem({
9 data,
10}: {
11 data: Partial<TodoItemRecord> & { id: string };
12}) {
13 const res = await fetch("/api/todo-items", {
14 method: "PATCH",
15 headers: {
16 "Content-Type": "application/json",
17 },
18 body: JSON.stringify(data),
19 });
20
21 if (!res.ok) {
22 throw new Error("Failed to update todo item");
23 }
24
25 const updatedItem: TodoItemRecord = await res.json();
26
27 return updatedItem;
28}
29
30async function insertTodoItem({ data }: { data: TodoItemCreateDataType }) {
31 const res = await fetch("/api/todo-items", {
32 method: "POST",
33 headers: {
34 "Content-Type": "application/json",
35 },
36 body: JSON.stringify(data),
37 });
38
39 if (!res.ok) {
40 throw new Error("Failed to insert todo item");
41 }
42
43 const response: TodoItemRecord = await res.json();
44
45 return response;
46}
47
48const todoItemsQueryKey = ["todo-items"];
49
50export const todoItemsCollection = createCollection<TodoItemRecord>(
51 queryCollectionOptions({
52 queryKey: todoItemsQueryKey,
53 queryFn: async ({ meta }) => {
54 const params = new URLSearchParams();
55
56 if (meta) {
57 const { where } = meta.loadSubsetOptions;
58
59 // Parse the expressions into simple format
60 const parsed = parseLoadSubsetOptions({ where });
61
62 // Build query parameters from parsed filters
63
64 // Add filters
65 parsed.filters.forEach(({ field, operator, value }) => {
66 const fieldName = field.join(".");
67
68 // Currently only the "eq" operator is supported by our API
69 if (operator === "eq") {
70 params.set(fieldName, String(value));
71 }
72 });
73 }
74
75 const res = await fetch(`/api/todo-items?${params}`, { method: "GET" });
76
77 const todoItems: TodoItemRecord[] = await res.json();
78
79 return todoItems;
80 },
81 queryClient: TanstackQuery.getContext().queryClient,
82 syncMode: "on-demand",
83 onInsert: async ({ transaction }) => {
84 const { modified: newTodoItem } = transaction.mutations[0];
85
86 try {
87 await insertTodoItem({
88 data: newTodoItem,
89 });
90 } catch (error) {
91 toast.error(`Failed to insert todo item "${newTodoItem.title}"`);
92 console.error("Failed to insert todo item:", error);
93 throw error;
94 }
95 },
96 onUpdate: async ({ transaction }) => {
97 /**
98 NOTE: This is a temporary solution for updating todo items.
99 **Do not use this in production code!**
100
101 Update strategy:
102 1. Optimistically update the local cache when a todo item is moved/updated
103 2. Update the server via API call
104 3. If the API call fails, refetch the data from the server and revert the local cache
105
106 The server state is only fetched from the server if the update fails.
107 Proper synchronization of moving/reordering items requires a sync engine
108 to handle client-server conflicts effectively, which is outside the scope
109 of this demo app.
110
111 Check out the available built-in sync collections here:
112 https://tanstack.com/db/latest/docs/overview#built-in-collection-types
113 */
114
115 const { original, changes } = transaction.mutations[0];
116
117 try {
118 // Send the updates to the server
119 await updateTodoItem({
120 data: {
121 id: original.id,
122 ...changes,
123 },
124 });
125
126 // Update the TanStack Query cache so switching projects shows correct data
127 const queryClient = TanstackQuery.getContext().queryClient;
128 queryClient.setQueriesData<TodoItemRecord[]>(
129 { queryKey: todoItemsQueryKey },
130 (oldData) => {
131 if (!oldData) return oldData;
132 return oldData.map((item) =>
133 item.id === original.id ? { ...item, ...changes } : item,
134 );
135 },
136 );
137 } catch (error) {
138 toast.error(`Failed to update todo item "${original.title}"`);
139
140 // TODO: handle this one later properly
141 // with queryClient.invalidateQueries(todoItemsQueryKey);
142 // // Do not sync if the collection is already refetching
143 // if (todoItemsCollection.utils.isRefetching === false) {
144 // // Sync back the server's data
145 // todoItemsCollection.utils.refetch();
146 // }
147 throw error;
148 }
149
150 // Do not sync back the server's data by default
151 return {
152 refetch: false,
153 };
154 },
155 getKey: (item) => item.id,
156 }),
157);