Open History to see the last commit
1import { createCollection } 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 getTodoItems() {
9 const res = await fetch("/api/todo-items", { method: "GET" });
10
11 const todoItems: TodoItemRecord[] = await res.json();
12
13 return todoItems;
14}
15
16async function updateTodoItem({
17 data,
18}: {
19 data: Partial<TodoItemRecord> & { id: string };
20}) {
21 const res = await fetch("/api/todo-items", {
22 method: "PATCH",
23 headers: {
24 "Content-Type": "application/json",
25 },
26 body: JSON.stringify(data),
27 });
28
29 if (!res.ok) {
30 throw new Error("Failed to update todo item");
31 }
32
33 const updatedItem: TodoItemRecord = await res.json();
34
35 return updatedItem;
36}
37
38async function insertTodoItem({ data }: { data: TodoItemCreateDataType }) {
39 const res = await fetch("/api/todo-items", {
40 method: "POST",
41 headers: {
42 "Content-Type": "application/json",
43 },
44 body: JSON.stringify(data),
45 });
46
47 if (!res.ok) {
48 throw new Error("Failed to insert todo item");
49 }
50
51 const response: TodoItemRecord = await res.json();
52
53 return response;
54}
55
56const todoItemsQueryKey = ["todo-items"];
57
58export const todoItemsCollection = createCollection<TodoItemRecord>(
59 queryCollectionOptions({
60 queryKey: todoItemsQueryKey,
61 queryFn: getTodoItems,
62 queryClient: TanstackQuery.getContext().queryClient,
63 onInsert: async ({ transaction }) => {
64 const { modified: newTodoItem } = transaction.mutations[0];
65
66 try {
67 await insertTodoItem({
68 data: newTodoItem,
69 });
70 } catch (error) {
71 toast.error(`Failed to insert todo item "${newTodoItem.title}"`);
72 console.error("Failed to insert todo item:", error);
73 }
74 },
75 onUpdate: async ({ transaction }) => {
76 /**
77 NOTE: This is a temporary solution for updating todo items.
78 **Do not use this in production code!**
79
80 Update strategy:
81 1. Optimistically update the local cache when a todo item is moved/updated
82 2. Update the server via API call
83 3. If the API call fails, refetch the data from the server and revert the local cache
84
85 The server state is only fetched from the server if the update fails.
86 Proper synchronization of moving/reordering items requires a sync engine
87 to handle client-server conflicts effectively, which is outside the scope
88 of this demo app.
89
90 Check out the available built-in sync collections here:
91 https://tanstack.com/db/latest/docs/overview#built-in-collection-types
92 */
93
94 const { original, changes } = transaction.mutations[0];
95
96 try {
97 // Send the updates to the server
98 await updateTodoItem({
99 data: {
100 id: original.id,
101 ...changes,
102 },
103 });
104
105 // If successful, we can keep the optimistic update
106 todoItemsCollection.utils.writeUpdate({
107 id: original.id,
108 ...changes,
109 });
110 } catch (_) {
111 toast.error(`Failed to update todo item "${original.title}"`);
112
113 // Do not sync if the collection is already refetching
114 if (todoItemsCollection.utils.isRefetching === false) {
115 // Sync back the server's data
116 todoItemsCollection.utils.refetch();
117 }
118 }
119
120 // Do not sync back the server's data by default
121 return {
122 refetch: false,
123 };
124 },
125 getKey: (item) => item.id,
126 }),
127);