Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

todoItems.ts

155 lines4.7 KB

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;
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;
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 "eq" operator is supported in the 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 }
94 },
95 onUpdate: async ({ transaction }) => {
96 /**
97 NOTE: This is a temporary solution for updating todo items.
98 **Do not use this in production code!**
99​
100 Update strategy:
101 1. Optimistically update the local cache when a todo item is moved/updated
102 2. Update the server via API call
103 3. If the API call fails, refetch the data from the server and revert the local cache
104​
105 The server state is only fetched from the server if the update fails.
106 Proper synchronization of moving/reordering items requires a sync engine
107 to handle client-server conflicts effectively, which is outside the scope
108 of this demo app.
109​
110 Check out the available built-in sync collections here:
111 https://tanstack.com/db/latest/docs/overview#built-in-collection-types
112 */
113​
114 const { original, changes } = transaction.mutations[0];
115​
116 try {
117 // Send the updates to the server
118 await updateTodoItem({
119 data: {
120 id: original.id,
121 ...changes,
122 },
123 });
124​
125 // Update the TanStack Query cache so switching projects shows correct data
126 const queryClient = TanstackQuery.getContext().queryClient;
127 queryClient.setQueriesData<TodoItemRecord[]>(
128 { queryKey: todoItemsQueryKey },
129 (oldData) => {
130 if (!oldData) return oldData;
131 return oldData.map((item) =>
132 item.id === original.id ? { ...item, ...changes } : item,
133 );
134 },
135 );
136 } catch (_) {
137 toast.error(`Failed to update todo item "${original.title}"`);
138​
139 // TODO: handle this one later properly
140 // with queryClient.invalidateQueries(todoItemsQueryKey);
141 // // Do not sync if the collection is already refetching
142 // if (todoItemsCollection.utils.isRefetching === false) {
143 // // Sync back the server's data
144 // todoItemsCollection.utils.refetch();
145 // }
146 }
147​
148 // Do not sync back the server's data by default
149 return {
150 refetch: false,
151 };
152 },
153 getKey: (item) => item.id,
154 }),
155);