Use on demand sync strategy for the todo items #38
Summary by CodeRabbit#
New Features
- Todo items now require project assignment with enforced DB constraint and index.
- API requests panel shows request search/query details.
- Improved filtering for todo items by project and board.
Bug Fixes
- Improved loading states, skeletons and UI layout stability across boards.
- Request tracking now uses full URL (href) for accurate routing and logging.
- More robust drag-and-drop and item reordering behavior.
Chores
- Updated TanStack dependencies.
- 1
🚀 Preview Deployment#
Status: ✅ Ready!
Preview URL: Open Preview
Commit:
85cb0d010980517160fdd4488f163a3e1e0d3ef0Built and deployed successfully
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/components/TodoBoards.tsx (1)
483-489: Sort comparator doesn't return 0 for equal elements, causing potentially unstable sort.The comparator returns
-1for both "Todo" and "In Progress", which doesn't properly establish ordering between them. This could lead to inconsistent board ordering across renders.🔎 Proposed fix
const sortedBoards = useMemo( () => - boards.sort((a) => - a.name === "Todo" ? -1 : a.name === "In Progress" ? -1 : 1, - ), + [...boards].sort((a, b) => { + const order = { "Todo": 0, "In Progress": 1, "Done": 2 }; + return (order[a.name as keyof typeof order] ?? 3) - (order[b.name as keyof typeof order] ?? 3); + }), [boards], );Note: Also using
[...boards]to avoid mutating the original array sincesort()mutates in place.🧹 Nitpick comments (2)
src/local-api/helpers.ts (1)
3-3: Consider removing unused type.The
Pathnametype alias appears to be unused after the schema change frompathnametohref. Consider removing it if it's no longer needed elsewhere.src/local-api/api.todo-items.ts (1)
68-68: Update variable type annotation.The type annotation references the schema but could be simplified for clarity.
🔎 Suggested simplification
- let newTodoItemData: z.infer<typeof todoItemCreateData>; + let newTodoItemData: TodoItemCreateDataType;📜 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 d9d8cbe749bb657558881fc860680409e6480bf3 and 4c47340ea9737f24170487432600d87a5f66a80d.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (18)
drizzle/migrations/0001_previous_chronomancer.sqldrizzle/migrations/meta/0001_snapshot.jsondrizzle/migrations/meta/_journal.jsonpackage.jsonpublic/sw.jssrc/client/pgliteHelpers.tssrc/collections/apiRequests.tssrc/collections/todoItems.tssrc/components/ApiRequestsPanel.tsxsrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/TodoBoardsLoading.tsxsrc/db/migrations.jsonsrc/db/schema.tssrc/db/seed.tssrc/integrations/tanstack-query/root-provider.tsxsrc/local-api/api.todo-items.tssrc/local-api/helpers.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/package.json
📄 CodeRabbit inference engine (AGENTS.md)
**/package.json: Always usepnpm installinstead ofnpm installfor installing dependencies Always usepnpm add <package>instead ofnpm install <package>for adding packages Always usepnpm add -D <package>instead ofnpm install --save-dev <package>for adding dev dependencies Always usepnpm remove <package>instead ofnpm uninstall <package>for removing packages Always usepnpm run <script>instead ofnpm run <script>for running scripts Always usepnpm dlx <command>instead ofnpx <command>Always usepnpm create <template>instead ofnpm create <template>Files:
package.json
package.json
📄 CodeRabbit inference engine (AGENTS.md)
package.json: Usepnpm devfor starting the development server Usepnpm buildfor production build Usepnpm run testfor running tests Usepnpm lintfor linting Usepnpm typecheckfor type checking Usepnpm formatfor code formatting Usepnpm db.generateto generate database migrations Usepnpm db.local.migrateto apply local migrations Usepnpm db.prod.migrateto apply production migrationsFiles:
package.json
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/db/schema.tssrc/client/pgliteHelpers.tssrc/integrations/tanstack-query/root-provider.tsxsrc/collections/apiRequests.tssrc/local-api/helpers.tssrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/ApiRequestsPanel.tsxsrc/db/seed.tssrc/collections/todoItems.tssrc/components/TodoBoardsLoading.tsxsrc/local-api/api.todo-items.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer functions over arrow functions for React components
Files:
src/db/schema.tssrc/client/pgliteHelpers.tssrc/integrations/tanstack-query/root-provider.tsxsrc/collections/apiRequests.tssrc/local-api/helpers.tssrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/ApiRequestsPanel.tsxsrc/db/seed.tssrc/collections/todoItems.tssrc/components/TodoBoardsLoading.tsxsrc/local-api/api.todo-items.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer
typeoverinterfacefor type definitionsFiles:
src/db/schema.tssrc/client/pgliteHelpers.tssrc/integrations/tanstack-query/root-provider.tsxsrc/collections/apiRequests.tssrc/local-api/helpers.tssrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/ApiRequestsPanel.tsxsrc/db/seed.tssrc/collections/todoItems.tssrc/components/TodoBoardsLoading.tsxsrc/local-api/api.todo-items.ts
🧠 Learnings (5)
📚 Learning: 2025-12-29T13:20:08.388Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-29T13:20:08.388Z Learning: Applies to package.json : Use `pnpm db.generate` to generate database migrationsApplied to files:
package.json
📚 Learning: 2025-12-29T13:20:08.388Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-29T13:20:08.388Z Learning: Applies to package.json : Use `pnpm db.local.migrate` to apply local migrationsApplied to files:
package.json
📚 Learning: 2025-12-29T13:20:08.388Z
Learnt from: CR Repo: fulopkovacs/trytanstackdb.com PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-29T13:20:08.388Z Learning: Applies to package.json : Use `pnpm db.prod.migrate` to apply production migrationsApplied to files:
package.json
📚 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/integrations/tanstack-query/root-provider.tsxsrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/ApiRequestsPanel.tsxsrc/components/TodoBoardsLoading.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/integrations/tanstack-query/root-provider.tsxsrc/components/CreateOrEditTodoItems.tsxsrc/components/TodoBoards.tsxsrc/components/ApiRequestsPanel.tsxsrc/components/TodoBoardsLoading.tsx
🧬 Code graph analysis (7)
src/client/pgliteHelpers.ts (3)
public/sw.js (2)
url(16-16)url(48-48)
src/local-api/index.ts (1)
API(6-10)
src/local-api/helpers.ts (1)
APIType(19-19)
src/integrations/tanstack-query/root-provider.tsx (1)
src/routes/__root.tsx (1)
MyRouterContext(22-24)
src/components/CreateOrEditTodoItems.tsx (2)
src/db/schema.ts (1)
TodoItemRecord(76-76)
src/collections/todoItems.ts (1)
todoItemsCollection(55-207)
drizzle/migrations/meta/_journal.json (1)
src/db/migrate.ts (1)
recordMigration(29-37)
src/components/TodoBoards.tsx (2)
src/components/TodoBoardsLoading.tsx (1)
LoadingTasksOnBoardSkeleton(7-19)
src/collections/todoItems.ts (1)
todoItemsCollection(55-207)
src/components/ApiRequestsPanel.tsx (1)
src/lib/utils.ts (1)
cn(4-6)
src/collections/todoItems.ts (1)
src/db/schema.ts (1)
TodoItemRecord(76-76)
🔇 Additional comments (28)
src/collections/apiRequests.ts (1)
13-13: LGTM!The addition of the optional
searchfield properly captures query parameters for API request tracking, aligning with the URL-based approach implemented inpgliteHelpers.ts.src/client/pgliteHelpers.ts (1)
74-89: LGTM!The shift from
pathnametohrefwith URL parsing correctly enables capturing both the path and query parameters. The handler lookup byurl.pathnamealigns with the API route structure, and storing bothpathnameandsearchprovides complete request tracking.src/components/CreateOrEditTodoItems.tsx (3)
23-24: LGTM!The addition of
projectIdto the required props correctly aligns with the database schema changes that add project-based organization to todo items.
55-55: LGTM!Including
projectIdin the insert operation is consistent with the updated schema and prop requirements.
45-47: No changes needed—synchronoustoArrayaccess is safe in this context.The collection data is guaranteed to be loaded because
CreateOrEditTodoItemsis rendered withinTodoBoards, which usesuseLiveQueryto load all todo items for the project (line 333). Users can only trigger the dialog afterTodoBoardshas already rendered with loaded data. The same synchronoustoArraypattern is already used elsewhere inTodoBoards(lines 379, 386, 426) with explicit comments confirming the data is "already-loaded collection data."package.json (1)
44-46: All TanStack dependency versions are valid and free from known vulnerabilities.Verification confirms that @tanstack/db@0.5.16, @tanstack/query-db-collection@1.0.12, and @tanstack/react-db@0.1.60 all exist on npm and are maintained by official TanStack developers with no reported security advisories.
src/components/TodoBoardsLoading.tsx (2)
7-19: LGTM!The new
LoadingTasksOnBoardSkeletoncomponent is well-structured and correctly exported for reuse inTodoBoards.tsx. The variable skeleton count based onboardIndexprovides visual variety during loading states.
21-44: LGTM!The refactor from
taskCounttoboardIndexprop cleanly delegates skeleton count determination toLoadingTasksOnBoardSkeleton, and the usage inTodoBoardsLoadingcorrectly passes board indices 0, 1, 2.src/local-api/helpers.ts (2)
21-25: LGTM!The schema update from
pathnametohrefwithz.url()validation is a good improvement. In Zod 4, standalone string format schemas likez.url()provide stronger validation. This aligns with the PR's shift to tracking full URLs for API requests.
50-68: LGTM!The
constructRequestForHandlerfunction correctly usesrequestData.hrefto construct theRequestobject, which accepts full URLs as the first argument.src/components/ApiRequestsPanel.tsx (2)
45-77: LGTM!The
JsonViewerenhancements are well-implemented:- The
defaultOpenprop provides flexibility for different use cases - The conditional rendering (
typeof data === "string" ? data : JSON.stringify(...)) correctly handles raw strings vs objects
84-157: LGTM!Good UI improvements:
- The
overflow-hiddenandshrink-0classes prevent layout shifts during expansion/collapse - Displaying
request.searchalongsidepathnameprovides better visibility into API request details - The new Search
JsonViewerwithdefaultOpen={!!request.search}is a nice UX touch
src/components/TodoBoards.tsx (3)
33-36: LGTM!Good refactoring to pass
todoItems,projectId,showTodoItemsLoading, andboardIndexas props. This enables better control over loading states and reduces the need for per-board queries.Also applies to: 173-185
430-433: Good defensive check.The null check for
overTodoItemwith early return prevents potential runtime errors when the drop target isn't found.
252-299: LGTM!The conditional rendering between
LoadingTasksOnBoardSkeletonand the sortable list is clean, and the integration withScrollShadow,DropIndicator, and virtualized rendering is well-structured.src/collections/todoItems.ts (1)
58-117: LGTM on the query function implementation.The dynamic query parameter building from
loadSubsetOptionsis well-structured, handling filters, sorting, limit, and offset appropriately.drizzle/migrations/meta/_journal.json (1)
11-18: LGTM!The new migration journal entry correctly follows the established format with proper index sequencing and version consistency.
drizzle/migrations/0001_previous_chronomancer.sql (1)
1-3: No action needed. This migration is safe.The
NOT NULLcolumn addition without aDEFAULTvalue works here becausetodo_itemsis empty when this migration runs. Migration 0000 creates the table and migration 0001 adds the column before any data is inserted. The subsequent seed data includesproject_idvalues for all todo items, so no constraint violation occurs.Likely an incorrect or invalid review comment.
public/sw.js (1)
82-82: LGTM! Improved URL handling.Sending the full
hrefinstead of justpathnamecorrectly preserves query parameters and other URL components, which aligns with the updated request handling in the main thread.src/db/schema.ts (2)
64-66: LGTM! Well-structured foreign key.The
projectIdfield is correctly defined with:- Appropriate foreign key reference to
projectsTable.id CASCADEdelete behavior to maintain referential integritynotNullconstraint matching the migration
72-72: LGTM! Good indexing strategy.Adding an index on
projectIdwill optimize queries filtering by project, which aligns with the new GET handler's query parameter support.src/db/seed.ts (2)
19-22: LGTM! Correct type refinement.The
TodoItemBasetype correctly omitsprojectIdsince it's added during record construction at line 218, following the same pattern asboardId.
213-221: LGTM! Consistent record construction.The
projectIdis correctly added to each todo item record during the mapping phase, maintaining consistency with the updated schema.src/local-api/api.todo-items.ts (2)
1-1: LGTM! Import added for array filtering.The
inArrayimport is correctly added to support the newboardId_inquery parameter functionality.
10-10: All internal client code already includesprojectId— validation enforced at API level.While making
projectIdrequired intodoItemCreateDatais a potential breaking change for external API consumers, all internal code paths in this codebase already properly passprojectId. TheCreateOrEditTodoItemscomponent requires bothboardIdandprojectId, and the API schema validation will catch any missing values at runtime. No action needed within this codebase.src/db/migrations.json (1)
17-21: No changes needed—migration strategy is appropriate for this development project.Adding a
NOT NULLcolumn without a default value is acceptable here because the seed script populatestodo_itemswith theprojectIdalready set (it's included in the mock data). The seed function is idempotent and checks for prior execution, so a fresh database setup handles this correctly. The development workflow (as documented in DEVELOPMENT.md) expects schema resets when schemas change, which aligns with this migration pattern for a pglite-based development database.drizzle/migrations/meta/0001_snapshot.json (2)
246-258: Confirm cascade delete behavior is intentional.The
todo_items_project_id_projects_id_fkforeign key usesON DELETE CASCADE, which means deleting a project will automatically delete all associated todo items. Combined with the cascade onboards.project_id, this creates a deletion chain: deleting a project removes all its boards and todo items.Verify this cascade behavior aligns with your data retention and user experience requirements.
194-231: LGTM: Index configuration supports project-based queries.The indexes are well-designed for the new project-based organization:
todo_items_project_id_idxenables efficient filtering of items by projecttodo_items_board_id_position_idxsupports ordered retrieval within boards
This aligns with the PR objective of using an on-demand sync strategy for todo items.
Resolvedby fuko@@ -0,0 +159,21 @@159+ "primaryKey": false,160+ "notNull": false161+ },162+ "created_at": {163+ "name": "created_at",164+ "type": "date",165+ "primaryKey": false,166+ "notNull": true167+ },168+ "board_id": {169+ "name": "board_id",170+ "type": "text",171+ "primaryKey": false,172+ "notNull": true173+ },174+ "project_id": {175+ "name": "project_id",176+ "type": "text",177+ "primaryKey": false,178+ "notNull": true179+ },⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# Find migration SQL files in the drizzle/migrations directory find drizzle/migrations -name "*.sql" -type f | head -20Repository: fulopkovacs/trytanstackdb.com
Length of output: 173
🏁 Script executed:
# Also check the structure of the migrations directory ls -la drizzle/migrations/Repository: fulopkovacs/trytanstackdb.com
Length of output: 398
🏁 Script executed:
cat drizzle/migrations/0001_previous_chronomancer.sqlRepository: fulopkovacs/trytanstackdb.com
Length of output: 451
🏁 Script executed:
cat drizzle/migrations/0000_outstanding_silvermane.sqlRepository: fulopkovacs/trytanstackdb.com
Length of output: 1573
Migration will fail on existing data — adding NOT NULL column without default or data population.
The migration SQL adds
project_idas a NOT NULL column directly to the existingtodo_itemstable:Migration excerpt
ALTER TABLE "todo_items" ADD COLUMN "project_id" text NOT NULL;This violates SQL constraints: you cannot add a NOT NULL column to a table with existing rows without either:
- Providing a DEFAULT value, OR
- Populating existing rows before applying the NOT NULL constraint
Any existing
todo_itemsrows will cause the migration to fail. Resolve by either:- Adding a DEFAULT value to the column in the migration, OR
- Backfilling existing rows with
project_idvalues before making the column NOT NULL
🤖 Prompt for AI Agents
In drizzle/migrations/meta/0001_snapshot.json around lines 174 to 179, the migration adds "project_id" as text NOT NULL which will fail on tables with existing todo_items rows; update the migration to either (A) add the column with a safe DEFAULT (e.g. ADD COLUMN project_id text DEFAULT '<default>' NOT NULL) or (B) add the column nullable, run a backfill/update to populate project_id for existing rows, then alter the column to NOT NULL — implement one of these approaches and ensure the snapshot/migration SQL reflects the chosen sequence so existing data won’t violate the NOT NULL constraint.@@ -1,2 +1,7 @@1-import { createCollection } from "@tanstack/db";1+import { createCollection, parseLoadSubsetOptions } from "@tanstack/db";22 import { queryCollectionOptions } from "@tanstack/query-db-collection";3+import type {4+ BasicExpression,5+ Offset,6+ OrderBy,7+} from "node_modules/@tanstack/db/dist/esm/query/ir";⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
cat -n src/collections/todoItems.ts | head -20Repository: fulopkovacs/trytanstackdb.com
Length of output: 884
🌐 Web query:
@tanstack/db types exports BasicExpression OrderBy💡 Result:
Yes — TanStack DB exposes those IR types. You can import them from @tanstack/db, for example:
import type { BasicExpression, OrderBy } from '@tanstack/db'
Docs: BasicExpression (type alias) and OrderBy (type alias = OrderByClause[]) are documented in the TanStack DB reference. [1] [2]
Sources [1] BasicExpression — TanStack DB docs. [2] OrderBy — TanStack DB docs.
🏁 Script executed:
# Search for other @tanstack/db imports in the codebase to identify patterns rg "@tanstack/db" --type ts --type tsx -B 2 -A 2Repository: fulopkovacs/trytanstackdb.com
Length of output: 100
🏁 Script executed:
# Search for Offset type in @tanstack/db documentation and check if it's in the main export rg "Offset" --type ts -B 1 -A 1 src/collections/todoItems.tsRepository: fulopkovacs/trytanstackdb.com
Length of output: 197
Import types from the main @tanstack/db entry point.
The types
BasicExpression,Offset, andOrderByare public exports from@tanstack/dband should not be imported from the internal pathnode_modules/@tanstack/db/dist/esm/query/ir. This file already imports from the main entry point on line 1; consolidate these type imports there to avoid relying on internal package structure that may change between versions.🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 3 to 7, the types BasicExpression, Offset, and OrderBy are being imported from an internal path (node_modules/@tanstack/db/dist/esm/query/ir); replace that by importing those types from the main @tanstack/db entry instead (consolidate them into the existing import at the top of the file), remove the internal-path import line, and ensure only public exports from @tanstack/db are referenced so the code no longer depends on internal package structure.✅ Addressed in commit 5db4211
@@ -58,4 +55,20 @@5855 export const todoItemsCollection = createCollection<TodoItemRecord>(5956 queryCollectionOptions({6057 queryKey: todoItemsQueryKey,61- queryFn: getTodoItems,58+ queryFn: async ({ meta }) => {59+ const params = new URLSearchParams();60+61+ if (meta) {62+ const { limit, offset, where, orderBy } = meta.loadSubsetOptions as {63+ where?: BasicExpression<boolean>;64+ orderBy?: OrderBy;65+ offset?: Offset;66+ limit?: number;67+ };68+69+ // Parse the expressions into simple format70+ const parsed = parseLoadSubsetOptions({ where, orderBy, limit });71+72+ console.info({73+ parsed,74+ });🛠️ Refactor suggestion | 🟠 Major
Remove debug logging before merging.
The
console.info({ parsed })statement appears to be debug code that should be removed for production.🔎 Proposed fix
// Parse the expressions into simple format const parsed = parseLoadSubsetOptions({ where, orderBy, limit }); - console.info({ - parsed, - }); - // Build query parameters from parsed filters📝 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.
🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 72 to 74, remove the leftover debug logging statement `console.info({ parsed })`; delete that line before merging and, if you need to record this information in production, replace it with a proper logger call at an appropriate log level or persist the data through the existing application logging/monitoring mechanism instead of using console.info.✅ Addressed in commits e4c2b18 to 21e953d
@@ -109,0 +167,21 @@167+ if (!oldData) return oldData;168+ return oldData.map((item) =>169+ item.id === original.id ? { ...item, ...changes } : item,170+ );171+ },172+ );173+174+ queryClient.setQueriesData<TodoItemRecord[]>(175+ { queryKey: todoItemsQueryKey },176+ (oldData) => {177+ console.log(178+ "Updating query cache, oldData:",179+ oldData?.length,180+ "items",181+ );182+ if (!oldData) return oldData;183+ return oldData.map((item) =>184+ item.id === original.id ? { ...item, ...changes } : item,185+ );186+ },187+ );⚠️ Potential issue | 🟡 Minor
Duplicate
setQueriesDatacalls.The two
setQueriesDatacalls perform the same operation on the same query key. The second call (lines 174-187) also adds a console.log that appears to be debug code. Remove the duplicate.🔎 Proposed fix
// Update the TanStack Query cache so switching projects shows correct data const queryClient = TanstackQuery.getContext().queryClient; queryClient.setQueriesData<TodoItemRecord[]>( { queryKey: todoItemsQueryKey }, (oldData) => { if (!oldData) return oldData; return oldData.map((item) => item.id === original.id ? { ...item, ...changes } : item, ); }, ); - - queryClient.setQueriesData<TodoItemRecord[]>( - { queryKey: todoItemsQueryKey }, - (oldData) => { - console.log( - "Updating query cache, oldData:", - oldData?.length, - "items", - ); - if (!oldData) return oldData; - return oldData.map((item) => - item.id === original.id ? { ...item, ...changes } : item, - ); - }, - );📝 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.
// Update the TanStack Query cache so switching projects shows correct data const queryClient = TanstackQuery.getContext().queryClient; queryClient.setQueriesData<TodoItemRecord[]>( { queryKey: todoItemsQueryKey }, (oldData) => { if (!oldData) return oldData; return oldData.map((item) => item.id === original.id ? { ...item, ...changes } : item, ); }, );🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 162 to 187 there are duplicate query cache updates: two identical queryClient.setQueriesData calls (the second from ~174–187 includes a debug console.log). Remove the duplicate second call and its console.log so only one setQueriesData call updates the todoItemsQueryKey; keep the existing correct update logic and ensure formatting/typing remains intact.✅ Addressed in commits e4c2b18 to 21e953d
@@ -376,0 +354,21 @@354+ if (355+ allTodoItems.length === 0 &&356+ todoItemsCollection.isLoadingSubset &&357+ !projectIds.includes(projectId)358+ ) {359+ setShowTodoItemsLoading(true);360+ setProjectIds((prev) => [...prev, projectId]);361+362+ unsubscribe = todoItemsCollection.on("loadingSubset:change", (event) => {363+ if (event.loadingSubsetTransition === "end") {364+ setShowTodoItemsLoading(false);365+ }366+ });367+ } else {368+ setShowTodoItemsLoading(false);369+ }370+371+ return () => {372+ unsubscribe?.();373+ };374+ }, [projectId, projectIds, allTodoItems.length]);⚠️ Potential issue | 🟡 Minor
The
projectIdsstate accumulates indefinitely and the effect has edge case concerns.projectIdsgrows unbounded as users switch projects, which could become a memory concern in long-running sessions.- The subscription is set up only when specific conditions are met, but
projectIdis in the dependency array—ifprojectIdchanges while loading is still in progress, the old subscription might not properly clean up before a new one is potentially created.
Consider using a
Setor clearing old entries, and potentially using a ref to track loading state per project:🔎 Suggested approach
- const [projectIds, setProjectIds] = useState<string[]>([]); + const loadedProjectIds = useRef(new Set<string>()); useEffect(() => { let unsubscribe: (() => void) | undefined; if ( allTodoItems.length === 0 && todoItemsCollection.isLoadingSubset && - !projectIds.includes(projectId) + !loadedProjectIds.current.has(projectId) ) { setShowTodoItemsLoading(true); - setProjectIds((prev) => [...prev, projectId]); + loadedProjectIds.current.add(projectId); unsubscribe = todoItemsCollection.on("loadingSubset:change", (event) => { if (event.loadingSubsetTransition === "end") { setShowTodoItemsLoading(false); } }); } else { setShowTodoItemsLoading(false); } return () => { unsubscribe?.(); }; - }, [projectId, projectIds, allTodoItems.length]); + }, [projectId, allTodoItems.length]);📝 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.
// TODO: not sure if this is necessary const loadedProjectIds = useRef(new Set<string>()); const [showTodoItemsLoading, setShowTodoItemsLoading] = useState<boolean>(false); useEffect(() => { let unsubscribe: (() => void) | undefined; if ( allTodoItems.length === 0 && todoItemsCollection.isLoadingSubset && !loadedProjectIds.current.has(projectId) ) { setShowTodoItemsLoading(true); loadedProjectIds.current.add(projectId); unsubscribe = todoItemsCollection.on("loadingSubset:change", (event) => { if (event.loadingSubsetTransition === "end") { setShowTodoItemsLoading(false); } }); } else { setShowTodoItemsLoading(false); } return () => { unsubscribe?.(); }; }, [projectId, allTodoItems.length]);🤖 Prompt for AI Agents
In src/components/TodoBoards.tsx around lines 345 to 374, the projectIds state accumulates indefinitely and the effect can leak subscriptions when projectId changes; replace projectIds state with a ref-based Set to track which projects have been observed (so it doesn't trigger re-renders or grow unbounded), ensure you remove/mark entries when finished or limit size if needed, and manage the subscription lifecycle deterministically by storing the unsubscribe in a ref and calling it synchronously before creating a new subscription when projectId changes; also guard subscription creation with the ref-set check so the effect only subscribes once per project and always cleans up the previous subscription on dependency change or unmount.✅ Addressed in commits e4c2b18 to 21e953d
@@ -1,7 +1,12 @@11 import { QueryClient, QueryClientProvider } from "@tanstack/react-query";223+// Singleton queryClient to ensure the same instance is used everywhere4+let queryClientSingleton: QueryClient | null = null;5+36 export function getContext() {4- const queryClient = new QueryClient();7+ if (!queryClientSingleton) {8+ queryClientSingleton = new QueryClient();9+ }510 return {6- queryClient,11+ queryClient: queryClientSingleton,712 };⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check getContext usage and SSR patterns echo "=== Searching for getContext usage in SSR contexts ===" rg -n "getContext" --type ts --type tsx -C 3 echo -e "\n=== Checking for server-side TanStack Start usage ===" rg -n "createStartHandler|StartServer" --type ts --type tsx -C 3 echo -e "\n=== Looking for route file patterns that might use SSR ===" fd -e tsx -e ts . src/routes/ 2>/dev/null --exec rg -l "loader|beforeLoad" {} \; 2>/dev/null || echo "No src/routes/ directory or no matches"Repository: fulopkovacs/trytanstackdb.com
Length of output: 515
🏁 Script executed:
#!/bin/bash echo "=== Reading root-provider.tsx file ===" cat -n src/integrations/tanstack-query/root-provider.tsx echo -e "\n=== Searching for getContext and queryClient usage ===" rg -n "getContext|queryClient" -C 3 echo -e "\n=== Checking the entire integrations directory structure ===" find src/integrations -type f -name "*.ts" -o -name "*.tsx" | head -20Repository: fulopkovacs/trytanstackdb.com
Length of output: 7393
🏁 Script executed:
#!/bin/bash echo "=== Searching for getRouter usage ===" rg -n "getRouter" -C 5 echo -e "\n=== Looking for entry.tsx or entry files ===" fd -type f \( -name "*entry*" -o -name "*start*" \) echo -e "\n=== Checking for TanStack Start handler pattern ===" rg -n "createStartHandler|StartServer" -C 3 echo -e "\n=== Looking for app initialization or root setup ===" head -50 src/main.tsx 2>/dev/null || head -50 src/index.tsx 2>/dev/null || echo "No main entry found, listing src root:" ls -la src/ | head -20Repository: fulopkovacs/trytanstackdb.com
Length of output: 2779
🏁 Script executed:
#!/bin/bash echo "=== Checking src/client directory ===" ls -la src/client/ echo -e "\n=== Checking src/server directory ===" ls -la src/server/ echo -e "\n=== Reading client entry if exists ===" if [ -f src/client/index.tsx ]; then cat -n src/client/index.tsx elif [ -f src/client/index.ts ]; then cat -n src/client/index.ts fi echo -e "\n=== Reading server entry if exists ===" if [ -f src/server/index.tsx ]; then cat -n src/server/index.tsx elif [ -f src/server/index.ts ]; then cat -n src/server/index.ts fi echo -e "\n=== Check for Vite entry points in root config ===" cat -n vite.config.ts 2>/dev/null | head -30Repository: fulopkovacs/trytanstackdb.com
Length of output: 1758
🏁 Script executed:
#!/bin/bash echo "=== Checking package.json for TanStack versions ===" rg -A 5 '"@tanstack/' package.json echo -e "\n=== Checking if routes use loaders or beforeLoad ===" rg -n "loader|beforeLoad" src/routes/ -C 2 | head -50 echo -e "\n=== Reading pgliteHelpers to understand SSR context ===" head -80 src/client/pgliteHelpers.tsRepository: fulopkovacs/trytanstackdb.com
Length of output: 5496
Remove module-level singleton—each SSR request must have isolated QueryClient instances.
The module-level
queryClientSingletoncauses query cache sharing across HTTP requests. In TanStack React Start with SSR,getRouter()is called per-request, sogetContext()retrieves the samequeryClientSingletonfor every user in the same Node process. This creates a data leak where queries and mutations from one user's session can be served to another user.Each request must receive its own
QueryClientinstance instead of reusing a shared singleton.🤖 Prompt for AI Agents
In src/integrations/tanstack-query/root-provider.tsx around lines 3 to 12, remove the module-level queryClientSingleton and stop reusing a shared QueryClient; instead instantiate and return a new QueryClient inside getContext() on every call so each SSR request gets an isolated client (optionally accept an initialState param and hydrate it per-request if needed); ensure no module-scoped cache remains and update any callers to rely on the per-call returned queryClient.✅ Addressed in commits e4c2b18 to 21e953d
@@ -30,2 +45,20 @@45+ .select()46+ .from(todoItemsTable)47+ .where(eq(todoItemsTable.boardId, boardId));48+ return json(results);49+ } else if (boardIdIn) {50+ const boardIds = boardIdIn.split(",");51+ const results = await db52+ .select()53+ .from(todoItemsTable)54+ .where(inArray(todoItemsTable.boardId, boardIds));55+ return json(results);56+ } else if (id) {57+ const results = await db58+ .select()59+ .from(todoItemsTable)60+ .where(eq(todoItemsTable.id, id));61+ return json(results);62+ }306331- return json(results);64+ return json([]);⚠️ Potential issue | 🟠 Major
Multiple issues with GET handler query parameter handling.
Breaking behavior change: Returns
[]when no query params provided instead of all items. This could break existing code expecting all items by default.Missing input validation: Line 50 uses
boardIdIn.split(",")without validating the result. Empty strings or invalid IDs could cause database errors or unexpected behavior.Ambiguous multi-param behavior: The if/else chain means only the first matching parameter is used. If a client sends both
projectIdandboardId, onlyprojectIdis used with no indication of the ignored parameter.Inconsistent naming:
boardId_inuses snake_case while the rest of the API uses camelCase.
🔎 Suggested improvements
GET: async ({ request }) => { const url = new URL(request.url); const projectId = url.searchParams.get("projectId"); const boardId = url.searchParams.get("boardId"); - const boardIdIn = url.searchParams.get("boardId_in"); + const boardIdIn = url.searchParams.get("boardIdIn"); const id = url.searchParams.get("id"); + + // Validate only one filter is provided + const filterCount = [projectId, boardId, boardIdIn, id].filter(Boolean).length; + if (filterCount > 1) { + return new Response("Only one filter parameter allowed", { status: 400 }); + } + if (filterCount === 0) { + return new Response("At least one filter parameter required", { status: 400 }); + } if (projectId) { const results = await db .select() .from(todoItemsTable) .where(eq(todoItemsTable.projectId, projectId)); return json(results); } else if (boardId) { const results = await db .select() .from(todoItemsTable) .where(eq(todoItemsTable.boardId, boardId)); return json(results); } else if (boardIdIn) { const boardIds = boardIdIn.split(","); + // Validate board IDs + if (boardIds.length === 0 || boardIds.some(id => !id.trim())) { + return new Response("Invalid boardIdIn parameter", { status: 400 }); + } const results = await db .select() .from(todoItemsTable) .where(inArray(todoItemsTable.boardId, boardIds)); return json(results); } else if (id) { const results = await db .select() .from(todoItemsTable) .where(eq(todoItemsTable.id, id)); return json(results); } - return json([]); + return new Response("Invalid query parameters", { status: 400 }); },✅ Addressed in commits e4c2b18 to 21e953d
Actionable comments posted: 1
♻️ Duplicate comments (2)
src/collections/todoItems.ts (2)
71-73: Remove debug logging before merging.This debug
console.infowas flagged in a previous review and should be removed for production.🔎 Proposed fix
// Parse the expressions into simple format const parsed = parseLoadSubsetOptions({ where, orderBy, limit }); - console.info({ - parsed, - }); - // Build query parameters from parsed filtersBased on past review comments, this should be removed.
161-186: DuplicatesetQueriesDatacalls with debug logging.The two
setQueriesDatacalls (lines 163-171 and 173-186) perform identical operations on the same query key. The second call includes aconsole.logthat appears to be debug code. This was flagged in a previous review and should be removed.🔎 Proposed fix
// Update the TanStack Query cache so switching projects shows correct data const queryClient = TanstackQuery.getContext().queryClient; queryClient.setQueriesData<TodoItemRecord[]>( { queryKey: todoItemsQueryKey }, (oldData) => { if (!oldData) return oldData; return oldData.map((item) => item.id === original.id ? { ...item, ...changes } : item, ); }, ); - - queryClient.setQueriesData<TodoItemRecord[]>( - { queryKey: todoItemsQueryKey }, - (oldData) => { - console.log( - "Updating query cache, oldData:", - oldData?.length, - "items", - ); - if (!oldData) return oldData; - return oldData.map((item) => - item.id === original.id ? { ...item, ...changes } : item, - ); - }, - );Based on past review comments, remove the duplicate call and its debug logging.
🧹 Nitpick comments (2)
src/collections/todoItems.ts (2)
111-115: Add error handling for fetch call.The fetch request lacks error handling. Network failures or non-OK responses will silently propagate, potentially causing the query to fail without clear error messages.
🔎 Proposed fix with error handling
const res = await fetch(`/api/todo-items?${params}`, { method: "GET" }); + if (!res.ok) { + throw new Error(`Failed to fetch todo items: ${res.status} ${res.statusText}`); + } + const todoItems: TodoItemRecord[] = await res.json(); return todoItems;
187-197: Incomplete error handling for update failures.When
updateTodoItemfails, the client cache may become out of sync with server state since no refetch or invalidation occurs. The TODO comment indicates this is known but unresolved.Consider implementing the commented-out invalidation logic to ensure cache consistency after failures:
🔎 Potential implementation
} catch (_) { toast.error(`Failed to update todo item "${original.title}"`); - // TODO: handle this one later properly - // with queryClient.invalidateQueries(todoItemsQueryKey); - // // Do not sync if the collection is already refetching - // if (todoItemsCollection.utils.isRefetching === false) { - // // Sync back the server's data - // todoItemsCollection.utils.refetch(); - // } + const queryClient = TanstackQuery.getContext().queryClient; + // Invalidate to refetch server state on next access + await queryClient.invalidateQueries({ queryKey: todoItemsQueryKey }); + return { refetch: true }; } - // Do not sync back the server's data by default - return { - refetch: false, - }; + return { refetch: false };Would you like me to open an issue to track implementing proper sync-back logic for update failures?
📜 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 4c47340ea9737f24170487432600d87a5f66a80d and 5db4211fa1128e57f9354fda09b9cc1557b25be6.
📒 Files selected for processing (1)
src/collections/todoItems.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/collections/todoItems.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer functions over arrow functions for React components
Files:
src/collections/todoItems.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer
typeoverinterfacefor type definitionsFiles:
src/collections/todoItems.ts
🧬 Code graph analysis (1)
src/collections/todoItems.ts (1)
src/db/schema.ts (1)
TodoItemRecord(76-76)
🔇 Additional comments (2)
src/collections/todoItems.ts (2)
1-5: Past import issue has been resolved.The types are now correctly accessed via the
IRnamespace imported from the main@tanstack/dbentry point, rather than from internal paths. This properly uses the public API.
118-118: LGTM! Sync mode aligns with PR objectives.The addition of
syncMode: "on-demand"correctly implements the PR's goal of using on-demand sync strategy for todo items.OutdatedResolvedby fuko@@ -58,4 +54,13 @@5854 export const todoItemsCollection = createCollection<TodoItemRecord>(5955 queryCollectionOptions({6056 queryKey: todoItemsQueryKey,61- queryFn: getTodoItems,57+ queryFn: async ({ meta }) => {58+ const params = new URLSearchParams();59+60+ if (meta) {61+ const { limit, offset, where, orderBy } = meta.loadSubsetOptions as {62+ where?: IR.BasicExpression<boolean>;63+ orderBy?: IR.OrderBy;64+ offset?: IR.Offset;65+ limit?: number;66+ };⚠️ Potential issue | 🟠 Major
Unsafe type assertion bypasses type safety.
The
asassertion onmeta.loadSubsetOptionsassumes the shape matches{ where?, orderBy?, offset?, limit? }without runtime validation. If the actual shape differs, this will cause silent runtime errors or incorrect behavior.Consider adding runtime validation or using type guards to ensure type safety before accessing these properties.
🔎 Suggested approach with type guard
+ // Type guard for load subset options + function isValidLoadSubsetOptions(opts: unknown): opts is { + where?: IR.BasicExpression<boolean>; + orderBy?: IR.OrderBy; + offset?: IR.Offset; + limit?: number; + } { + return typeof opts === 'object' && opts !== null; + } + if (meta) { - const { limit, offset, where, orderBy } = meta.loadSubsetOptions as { - where?: IR.BasicExpression<boolean>; - orderBy?: IR.OrderBy; - offset?: IR.Offset; - limit?: number; - }; + if (!isValidLoadSubsetOptions(meta.loadSubsetOptions)) { + throw new Error('Invalid loadSubsetOptions shape'); + } + const { limit, offset, where, orderBy } = meta.loadSubsetOptions;Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/collections/todoItems.ts around lines 61 to 66, the inline "as" type assertion on meta.loadSubsetOptions unsafely assumes it has {where?, orderBy?, offset?, limit?}; replace the assertion with a runtime type guard or validation: implement a small isLoadSubsetOptions(obj): obj is {where?:..., orderBy?:..., offset?:..., limit?: number} that checks obj is an object and that each optional property has the expected shape/primitive (e.g. typeof limit === 'number', offset object shape, etc.), call this guard before reading properties, and fall back to safe defaults when the guard fails (or handle error); update the code to destructure from the validated object only after the guard passes.fuko merged thisea52f33
fuko closed this
Sign in to join this conversation.
Warning
Rate limit exceeded#
@fulopkovacs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 4 minutes and 57 seconds before requesting another review.
⌛ How to resolve this issue?
After the wait time has elapsed, a review can be triggered using the
@coderabbitai reviewcommand as a PR comment. Alternatively, push new commits to this PR.We recommend that you space out your commits to avoid hitting the rate limit.
🚦 How do rate limits work?
CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.
📥 Commits
Reviewing files that changed from the base of the PR and between 5db4211fa1128e57f9354fda09b9cc1557b25be6 and 85cb0d010980517160fdd4488f163a3e1e0d3ef0.
📒 Files selected for processing (4)
src/collections/todoItems.tssrc/components/TodoBoards.tsxsrc/integrations/tanstack-query/root-provider.tsxsrc/local-api/api.todo-items.tsWalkthrough#
Adds a required project_id foreign key to todo_items (DB + migrations) and propagates that change through API handlers, collection query behavior, request-tracking (href instead of pathname), and UI components to support project-scoped todo items and cache-driven on-demand syncing.
Changes#
drizzle/migrations/0001_previous_chronomancer.sql,drizzle/migrations/meta/0001_snapshot.json,drizzle/migrations/meta/_journal.json,src/db/schema.ts,src/db/migrations.jsonproject_id/projectIdtotodo_items, create FKtodo_items_project_id_projects_id_fk→projects(id)(ON DELETE CASCADE), add indextodo_items_project_id_idx, and append migration metadata/journal snapshot.src/local-api/api.todo-items.ts,src/local-api/helpers.ts{ request }and parses URL query params (projectId, boardId, boardId_in, id); create schema requiresprojectId. Helpers and RequestData switched frompathnametohref(z.url()).public/sw.js,src/client/pgliteHelpers.ts,src/local-api/helpers.ts,src/collections/apiRequests.tshref, pgliteHelpers constructs URL and uses url.pathname & url.search, RequestData shape renamed (pathname→href), andApiRequestgained optionalsearch?: string.src/collections/todoItems.tsqueryFnusingmeta.loadSubsetOptions(parseLoadSubsetOptions) to build query string; addsyncMode: "on-demand"; migrate optimistic/writeUpdate flows to explicit Query Cache updates (setQueriesData) for insert/update; return refetch control for updates.src/components/TodoBoards.tsx,src/components/TodoBoardsLoading.tsx,src/components/CreateOrEditTodoItems.tsxprojectIdon creation.src/components/ApiRequestsPanel.tsxrequest.search, small UI refinements.src/db/seed.ts,src/integrations/tanstack-query/root-provider.tsx,package.jsonprojectIdto generated todo items andTodoItemBaseomitsprojectId. Introduce a module-level QueryClient singleton. Bump@tanstackpackages to newer patch/minor versions.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs#
src/collections/todoItems.ts(collection/query and cache sync); strong overlap with collection changes here.href/pathname, UI rendering); closely related to WWW/request plumbing updates.src/components/ApiRequestsPanel.tsxUI/overflow behavior; likely overlaps with panel layout changes here.Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
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