Add a temporary solution for handling conflicts between the remote state and client-side cache when moving todo items #37
Summary by CodeRabbit#
Bug Fixes
- Insert and update failures now surface as error toasts and trigger data refresh when needed.
Improvements
- Drag/position changes apply immediately for a snappier experience.
- Optimistic updates are kept on successful server sync; failed syncs show an error and refresh data.
Removals
- Server-side batch-update endpoint and debounced batch persistence have been removed.
- 1
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/collections/todoItems.ts (1)
38-57: Address the unused export warning.The
batchUpdateTodoItemfunction is exported but never used according to the pipeline failure. Since the PR moves to per-item updates, this appears to be dead code that should either be removed or marked for future use.Consider either:
- Removing the function if it's no longer needed
- Removing the
exportkeyword if it's only used internally - Adding a comment explaining why it's kept for future use
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between f9aac14d044c7c05e6ee3a07fe32bdb3dc3cc55a and 6810aafe789d4598bb375081128491872ceea125.
📒 Files selected for processing (3)
src/collections/todoItems.tssrc/components/TodoBoards.tsxsrc/local-api/api.todo-items.ts
🧰 Additional context used
📓 Path-based instructions (3)
src/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Always ensure no formatting/linting issues exist in code - use
pnpm check --fixto automatically fix issuesFiles:
src/components/TodoBoards.tsxsrc/local-api/api.todo-items.tssrc/collections/todoItems.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer functions over arrow functions for React components
Files:
src/components/TodoBoards.tsxsrc/local-api/api.todo-items.tssrc/collections/todoItems.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer
typeoverinterfacefor type definitionsFiles:
src/components/TodoBoards.tsxsrc/local-api/api.todo-items.tssrc/collections/todoItems.ts
🧠 Learnings (2)
📚 Learning: 2025-12-24T15:25:07.106Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 22 File: src/components/TodoBoards.tsx:63-81 Timestamp: 2025-12-24T15:25:07.106Z Learning: In Tailwind CSS v4, prefer canonical classes using bg-linear-to-* (e.g., bg-linear-to-b, bg-linear-to-t, bg-linear-to-r) over the older bg-gradient-to-* syntax. This aligns with Tailwind LSP's suggestCanonicalClasses rule. Apply across TSX files (e.g., src/components/*.tsx); replace occurrences of bg-gradient-to-* with the corresponding bg-linear-to-* equivalents and verify gradients visually.Applied to files:
src/components/TodoBoards.tsx
📚 Learning: 2025-12-28T23:34:13.416Z
Learnt from: fulopkovacs Repo: fulopkovacs/trytanstackdb.com PR: 32 File: src/components/HomeIntro.tsx:16-25 Timestamp: 2025-12-28T23:34:13.416Z Learning: In Motion (motion/react), when configuring variant transitions, use delayChildren: stagger(x) to create per-child delays (e.g., delayChildren: stagger(0.2)). This is different from the older API that used a separate staggerChildren property. Apply this guidance to TSX files that declare motion variants (e.g., in src/components/**/*.tsx) and verify that stagger is imported from framer-motion. Ensure transitions reflect the intended stagger timing and that no conflicting delay values override the staggered effect.Applied to files:
src/components/TodoBoards.tsx
🧬 Code graph analysis (2)
src/components/TodoBoards.tsx (3)
src/collections/todoItems.ts (1)
todoItemsCollection(79-148)
src/local-api/api.batch.todo-items.ts (1)
updatedData(11-49)
src/components/PriorityRating.tsx (1)
index(33-37)
src/collections/todoItems.ts (1)
src/db/schema.ts (1)
TodoItemRecord(72-72)
🪛 GitHub Actions: CI/CD
src/collections/todoItems.ts
[warning] 38-38: Unused exports: 'batchUpdateTodoItem' is defined but never used. (no-unused-vars)
🔇 Additional comments (5)
src/collections/todoItems.ts (3)
55-56: Type assertion is unavoidable here.The TODO comment about avoiding type casting is noted. Since the API contract is established and validated server-side with Zod schemas, this type assertion is reasonable and safe.
77-81: Good practice: Extracting the query key constant.Defining
todoItemsQueryKeyas a constant and using it in the collection options improves maintainability and makes it easier to reference the same query key elsewhere if needed.
97-144: Remove the manualwriteUpdatecall — it's redundant.The optimistic update is already applied when
collection.update()is called (before the onUpdate handler runs). CallingwriteUpdate()in the success path with identicalchangeshas no effect and adds unnecessary code. Since you're returning{ refetch: false }, the optimistic state already stands after server confirmation. If you need to fetch the latest server state instead, removerefetch: falseand let TanStack handle the sync automatically.src/components/TodoBoards.tsx (2)
307-322: Clean refactoring from batch to per-item updates.The new
updateTodoPositionfunction simplifies the update logic by directly mutating the item through the collection'supdatemethod. The implementation correctly handles both position-only updates and board changes, with error handling delegated to the collection'sonUpdatehandler.
400-404: LGTM: Consistent usage of the new update pattern.All three call sites correctly use
updateTodoPositionwith appropriate parameters for their specific scenarios (empty column drop, same-column reorder, and cross-column move).Also applies to: 427-430, 449-453
@@ -109,9 +109,10 @@109109 return new Response(`No columns to update`, { status: 400 });110110 }111111112- const results = await db112+ const [updatedTodoItemData] = await db113113 .update(todoItemsTable)114114 .set(updatedData)115- .where(eq(todoItemsTable.id, updatedData.id));115+ .where(eq(todoItemsTable.id, updatedData.id))116+ .returning();116117117- return json(results);118+ return json(updatedTodoItemData);⚠️ Potential issue | 🔴 Critical
Add error handling for when the todo item is not found.
The destructuring assumes the update will always find a matching item. If
updatedData.iddoesn't exist in the database,updatedTodoItemDatawill beundefined, causing the endpoint to returnjson(undefined)with a 200 status code instead of a proper error response.🔎 Proposed fix
const [updatedTodoItemData] = await db .update(todoItemsTable) .set(updatedData) .where(eq(todoItemsTable.id, updatedData.id)) .returning(); +if (!updatedTodoItemData) { + return new Response(`Todo item not found`, { status: 404 }); +} + return json(updatedTodoItemData);📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const [updatedTodoItemData] = await db .update(todoItemsTable) .set(updatedData) .where(eq(todoItemsTable.id, updatedData.id)) .returning(); if (!updatedTodoItemData) { return new Response(`Todo item not found`, { status: 404 }); } return json(updatedTodoItemData);🤖 Prompt for AI Agents
In src/local-api/api.todo-items.ts around lines 112–118, the code destructures the update result and returns json(updatedTodoItemData) without checking if the DB found a matching id; change the flow to detect when the update returned no rows (updatedTodoItemData is undefined) and return a proper 404 error response (e.g., return json({ error: "Todo item not found" }, { status: 404 }) or throw an HTTP error) instead of returning json(undefined); ensure you still return the updated item when present.✅ Addressed in commits de2f1e9 to a167793
🚀 Preview Deployment#
Status: ✅ Ready!
Preview URL: Open Preview
Commit:
a16779385bab4ea965e7ba891ff1dce67de1bb04Built and deployed successfully
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/local-api/api.todo-items.ts (1)
112-118: Add error handling for when the todo item is not found.The destructuring assumes the update will always find a matching item. If
updatedData.iddoesn't exist in the database,updatedTodoItemDatawill beundefined, causing the endpoint to returnjson(undefined)with a 200 status code instead of a proper error response.🔎 Proposed fix
const [updatedTodoItemData] = await db .update(todoItemsTable) .set(updatedData) .where(eq(todoItemsTable.id, updatedData.id)) .returning(); +if (!updatedTodoItemData) { + return new Response(`Todo item not found`, { status: 404 }); +} + return json(updatedTodoItemData);🧹 Nitpick comments (1)
src/collections/todoItems.ts (1)
110-110: Log the error for better debugging.The error is caught with
_but not logged, making it harder to debug API failures. This is inconsistent with the error handling in theonInsertcallback (line 72) which logs errors to the console.🔎 Proposed fix
- } catch (_) { + } catch (error) { toast.error(`Failed to update todo item "${original.title}"`); + console.error("Failed to update todo item:", error); // Abort all ongoing sync queries📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 6810aafe789d4598bb375081128491872ceea125 and b533889b4fde140a8ae5954f9dd0370441f54f4d.
📒 Files selected for processing (4)
src/collections/todoItems.tssrc/local-api/api.batch.todo-items.tssrc/local-api/api.todo-items.tssrc/local-api/index.ts
💤 Files with no reviewable changes (2)
- src/local-api/api.batch.todo-items.ts
- src/local-api/index.ts
🧰 Additional context used
📓 Path-based instructions (3)
src/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Always ensure no formatting/linting issues exist in code - use
pnpm check --fixto automatically fix issuesFiles:
src/local-api/api.todo-items.tssrc/collections/todoItems.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer functions over arrow functions for React components
Files:
src/local-api/api.todo-items.tssrc/collections/todoItems.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer
typeoverinterfacefor type definitionsFiles:
src/local-api/api.todo-items.tssrc/collections/todoItems.ts
🧬 Code graph analysis (2)
src/local-api/api.todo-items.ts (3)
src/db/index.ts (1)
db(13-15)
src/db/schema.ts (1)
todoItemsTable(54-70)
src/local-api/helpers.ts (1)
json(29-43)
src/collections/todoItems.ts (1)
src/db/schema.ts (1)
TodoItemRecord(72-72)
🔇 Additional comments (2)
src/collections/todoItems.ts (2)
56-60: LGTM! Good refactor to improve type safety and maintainability.The introduction of
todoItemsQueryKeyas a constant and making the collection generic withTodoItemRecordimproves code maintainability and type inference.
76-92: Good documentation of the temporary nature of this solution.The warning about not using this in production and the clear explanation of the update strategy helps reviewers understand the limitations and trade-offs.
Resolvedby fuko@@ -95,12 +92,18 @@92+ */93+9594 const { original, changes } = transaction.mutations[0];96959796 try {97+ // Send the updates to the server9898 await updateTodoItem({9999 data: {100100 id: original.id,101101 ...changes,102102 },103103 });104- } catch (error) {105- // TODO: handle error106- console.error("Failed to update todo item:", error);104+105+ // If successful, we can keep the optimistic update106+ todoItemsCollection.utils.writeUpdate({107+ id: original.id,108+ ...changes,109+ });⚠️ Potential issue | 🟠 Major
Remove redundant
writeUpdatecall after successful API update.In an optimistic update pattern, the local cache is already updated before the server call. After the server confirms success, you should either:
- Keep the optimistic update as-is (do nothing), or
- Update with the server's response if the server might have modified the data
Calling
writeUpdateagain with the same data is redundant and could cause unnecessary re-renders or race conditions. Since the API returns the updated item (line 33 in api.todo-items.ts), consider using that response to ensure the local state matches the server state.🔎 Proposed fix (Option 1: Use server response)
try { // Send the updates to the server - await updateTodoItem({ + const serverItem = await updateTodoItem({ data: { id: original.id, ...changes, }, }); - // If successful, we can keep the optimistic update - todoItemsCollection.utils.writeUpdate({ - id: original.id, - ...changes, - }); + // Update with server response to ensure consistency + todoItemsCollection.utils.writeUpdate(serverItem); } catch (_) {🔎 Proposed fix (Option 2: Remove redundant call)
try { // Send the updates to the server await updateTodoItem({ data: { id: original.id, ...changes, }, }); - // If successful, we can keep the optimistic update - todoItemsCollection.utils.writeUpdate({ - id: original.id, - ...changes, - }); + // If successful, keep the optimistic update (already applied) } catch (_) {Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 106 to 109, the code calls todoItemsCollection.utils.writeUpdate after the API update which is redundant for an optimistic update; instead, use the server response to reconcile local state or remove the extra writeUpdate. Change the flow so that after awaiting the API call you either (A) apply the server-returned item to the local cache (replace/update the entry with the response payload) to ensure server-canonical fields are used, or (B) simply omit the second writeUpdate entirely if no server-side changes are expected; implement option A if the API (api.todo-items.ts line 33) returns an updated item.@@ -100,7 +100,18 @@100100 id: original.id,101101 ...changes,102102 },103103 });104- } catch (error) {105- // TODO: handle error106- console.error("Failed to update todo item:", error);104+105+ // If successful, we can keep the optimistic update106+ todoItemsCollection.utils.writeUpdate({107+ id: original.id,108+ ...changes,109+ });110+ } catch (_) {111+ toast.error(`Failed to update todo item "${original.title}"`);112+113+ // Abort all ongoing sync queries114+ if (todoItemsCollection.utils.isRefetching === false) {115+ // Sync back the server's data116+ todoItemsCollection.utils.refetch();117+ }⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Search for isRefetching usage patterns echo "=== Searching for isRefetching usage ===" rg -n 'isRefetching' --type ts --type tsx -C 3 echo -e "\n=== Searching for collection.utils patterns ===" rg -n 'collection\.utils\.' --type ts --type tsx -C 2 echo -e "\n=== Searching for TanStack imports ===" rg -n 'tanstack|@tanstack' --type ts --type tsx -iRepository: fulopkovacs/trytanstackdb.com
Length of output: 303
🌐 Web query:
TanStack DB collection utils isRefetching property API documentation💡 Result:
The QueryCollectionUtils API exposes an isRefetching boolean property:
- Signature: isRefetching: boolean.
- Meaning: true when the associated query is performing a background refetch (not the initial fetch). [1][2]
Sources: [1] TanStack DB — QueryCollectionUtils (API reference). [2] TanStack Query — useQuery (isRefetching explanation).
🏁 Script executed:
#!/bin/bash # Search for isRefetching usage patterns (fixed file type) echo "=== Searching for isRefetching usage ===" rg -n 'isRefetching' -C 3 echo -e "\n=== Check the specific file mentioned ===" cat -n src/collections/todoItems.ts | sed -n '110,120p' echo -e "\n=== Search for other refetch calls and context ===" rg -n 'refetch' src/collections/todoItems.ts -C 2Repository: fulopkovacs/trytanstackdb.com
Length of output: 1797
Update the comment to clarify the actual behavior.
The comment "Abort all ongoing sync queries" is misleading. The code doesn't abort queries—it calls
refetch(). The condition checks if no refetch is currently in progress before triggering a new one, which correctly prevents duplicate calls. Update the comment to reflect this intent, e.g., "Sync back the server's data if not already refetching" or "Refetch data from server if not currently refetching."🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 114 to 117 the inline comment "Abort all ongoing sync queries" is inaccurate: the code checks if todoItemsCollection.utils.isRefetching === false and then calls todoItemsCollection.utils.refetch(), so it prevents duplicate refetches rather than aborting anything; update the comment to accurately describe behavior such as "Refetch data from server if not currently refetching" or "Sync back the server's data if not already refetching" so the comment matches the logic.✅ Addressed in commits de2f1e9 to a167793
fuko merged thisd9d8cbe
fuko closed this
Sign in to join this conversation.
Walkthrough#
Removes batched/debounced todo-item persistence and the batch API, makes todoItemsCollection generic with a new query key, implements immediate per-item optimistic updates with server PATCH per item, and changes the PATCH API to return a single updated item.
Changes#
src/collections/todoItems.tsbatchUpdateTodoItem. AddedtodoItemsQueryKeyconstant. ExportedtodoItemsCollectionnow created ascreateCollection<TodoItemRecord>(...). Insert error handling preserved; onUpdate implements optimistic local update, sends server mutation, and returnsrefetch: false.src/components/TodoBoards.tsxusePacedMutations,debounceStrategy,batchUpdateTodoItem) and replaced with immediate per-item persistence viatodoItemsCollection.update(itemId, { boardId, position }). Drag-end logic now calls direct collection update.src/local-api/api.todo-items.tstodoItemUpdateDatais now internal (not exported). PATCH handler uses.returning()and returns a single updated item (json(updatedTodoItemData)); added 404 handling when no item is updated.src/local-api/api.batch.todo-items.ts,src/local-api/index.ts/api/batch/todo-itemsmapping fromsrc/local-api/index.ts, dropping related imports/exports.Sequence Diagram(s)#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~22 minutes
Possibly related PRs#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning, 1 inconclusive)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (1 passed)
✨ Finishing touches
📜 Recent review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between b533889b4fde140a8ae5954f9dd0370441f54f4d and a16779385bab4ea965e7ba891ff1dce67de1bb04.
📒 Files selected for processing (2)
src/collections/todoItems.tssrc/local-api/api.todo-items.ts🧰 Additional context used
📓 Path-based instructions (3)
src/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/collections/todoItems.tssrc/local-api/api.todo-items.ts**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/collections/todoItems.tssrc/local-api/api.todo-items.ts**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Files:
src/collections/todoItems.tssrc/local-api/api.todo-items.ts🧬 Code graph analysis (2)
src/collections/todoItems.ts (2)
src/local-api/api.todo-items.ts (2)
🔇 Additional comments (5)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share