Open History to see the last commit
1# domain_map.yaml
2# Generated by skill-domain-discovery
3# Library: @tanstack/db
4# Version: 0.5.30
5# Date: 2026-03-04
6# Status: reviewed
7
8library:
9 name: '@tanstack/db'
10 version: '0.5.30'
11 repository: 'https://github.com/TanStack/db'
12 description: 'Reactive client store with normalized collections, sub-millisecond live queries, and instant optimistic mutations'
13 primary_framework: 'framework-agnostic (React, Vue, Svelte, Solid, Angular adapters)'
14
15domains:
16 - name: 'Collection Setup & Schema'
17 slug: 'collection-setup'
18 description: 'Creating and configuring typed collections from any data source, with optional schema validation, type transformations, and adapter-specific sync patterns'
19
20 - name: 'Live Query Construction'
21 slug: 'live-queries'
22 description: 'Building SQL-like reactive queries across collections using the fluent query builder API with expressions, joins, aggregations, and derived collections'
23
24 - name: 'Framework Integration'
25 slug: 'framework-integration'
26 description: 'Binding live queries to UI framework components using framework-specific hooks, dependency tracking, Suspense, and pagination'
27
28 - name: 'Mutations & Optimistic State'
29 slug: 'mutations-optimistic'
30 description: 'Writing data to collections with instant optimistic feedback, managing transaction lifecycles, and handling rollback on failure'
31
32 - name: 'Meta-Framework Integration'
33 slug: 'meta-framework'
34 description: 'Client-side preloading of collections in route loaders for TanStack Start/Router, Next.js, Remix, Nuxt, and SvelteKit — ensuring data is ready before component render'
35
36 - name: 'Custom Adapter Authoring'
37 slug: 'custom-adapter'
38 description: 'Building custom collection adapters that implement the SyncConfig contract for new backends'
39
40 - name: 'Offline Transactions'
41 slug: 'offline'
42 description: 'Offline-first transaction queueing with persistence, retry, multi-tab coordination, and connectivity detection'
43
44skills:
45 - name: 'Collection Setup'
46 slug: 'collection-setup'
47 domain: 'collection-setup'
48 description: 'Creating and configuring typed collections backed by any data source'
49 type: 'core'
50 covers:
51 - 'createCollection'
52 - 'queryCollectionOptions (@tanstack/query-db-collection)'
53 - 'electricCollectionOptions (@tanstack/electric-db-collection)'
54 - 'trailbaseCollectionOptions (@tanstack/trailbase-db-collection)'
55 - 'powerSyncCollectionOptions (@tanstack/powersync-db-collection)'
56 - 'rxdbCollectionOptions (@tanstack/rxdb-db-collection)'
57 - 'localOnlyCollectionOptions'
58 - 'localStorageCollectionOptions'
59 - 'CollectionConfig interface (id, getKey, schema, sync, compare, autoIndex, startSync, gcTime, utils)'
60 - 'StandardSchema integration (Zod, Valibot, ArkType, Effect)'
61 - 'Schema validation (TInput vs TOutput, transformations, defaults)'
62 - 'Collection lifecycle (idle -> loading -> initialCommit -> ready -> error -> cleaned-up)'
63 - 'Collection status tracking (isReady, isLoading, isError, isCleanedUp)'
64 - 'localOnly -> real backend upgrade path'
65 - 'Adapter-specific sync patterns (Electric txid, Query direct writes, PowerSync persistence)'
66 - 'Sync modes (eager, on-demand, progressive)'
67 tasks:
68 - 'Create a collection backed by TanStack Query for REST API data'
69 - 'Create a collection synced with ElectricSQL for real-time Postgres data'
70 - 'Create a local-only collection for temporary UI state'
71 - 'Add schema validation with type transformations (e.g. string -> Date)'
72 - 'Configure collection with custom getKey, gcTime, and autoIndex'
73 - 'Create a localStorage collection for cross-tab persistent state'
74 - 'Configure PowerSync collection with custom serializer'
75 - 'Prototype with localOnlyCollectionOptions then swap to a real backend'
76 - 'Configure on-demand sync mode for large datasets'
77 - 'Track Electric txid to prevent optimistic state flash'
78 - 'Use direct writes to update query collection without refetch'
79 subsystems:
80 - name: 'TanStack Query adapter'
81 package: '@tanstack/query-db-collection'
82 config_surface: 'queryKey, queryFn, queryClient, select, enabled, refetchInterval, staleTime, syncMode'
83 - name: 'ElectricSQL adapter'
84 package: '@tanstack/electric-db-collection'
85 config_surface: 'shapeOptions, syncMode (eager/on-demand/progressive), txid tracking via awaitTxId/awaitMatch'
86 - name: 'PowerSync adapter'
87 package: '@tanstack/powersync-db-collection'
88 config_surface: 'database, table, conversions, batchSize, syncMode'
89 - name: 'RxDB adapter'
90 package: '@tanstack/rxdb-db-collection'
91 config_surface: 'rxCollection, syncBatchSize; keys always strings'
92 - name: 'TrailBase adapter'
93 package: '@tanstack/trailbase-db-collection'
94 config_surface: 'recordApi, conversions'
95 - name: 'Local-only'
96 package: '@tanstack/db'
97 config_surface: 'getKey, schema, initialData'
98 - name: 'localStorage'
99 package: '@tanstack/db'
100 config_surface: 'storageKey, getKey, schema'
101 failure_modes:
102 - mistake: 'queryFn returning empty array deletes all collection data'
103 mechanism: "queryCollectionOptions treats queryFn result as complete server state; returning [] means 'server has no items', causing all existing items to be deleted from the collection"
104 wrong_pattern: |
105 queryFn: async () => {
106 const res = await fetch('/api/todos?status=active')
107 return res.json() // returns [] when no active todos
108 }
109 correct_pattern: |
110 queryFn: async () => {
111 const res = await fetch('/api/todos') // fetch ALL todos
112 return res.json()
113 }
114 // Or use on-demand sync mode for filtered queries
115 source: 'docs/collections/query-collection.md - Full State Sync section'
116 priority: 'CRITICAL'
117 skills: ['collection-setup']
118
119 - mistake: 'Not knowing which collection type to use for a given backend'
120 mechanism: 'AI agents default to bare createCollection or localOnlyCollectionOptions when they should use queryCollectionOptions, electricCollectionOptions, etc.; each adapter handles sync, handlers, and utilities differently'
121 source: 'maintainer interview'
122 priority: 'CRITICAL'
123 skills: ['collection-setup']
124
125 - mistake: 'Using async schema validation'
126 mechanism: 'Schema validation must be synchronous; returning a Promise from a schema throws SchemaMustBeSynchronousError, but the error only surfaces at mutation time, not at collection creation'
127 source: 'packages/db/src/collection/mutations.ts:101'
128 priority: 'HIGH'
129 skills: ['collection-setup']
130
131 - mistake: 'getKey returning undefined for some items'
132 mechanism: "If getKey returns undefined for any item, throws UndefinedKeyError; common when accessing a nested property that doesn't exist on all items"
133 source: 'packages/db/src/collection/mutations.ts:148'
134 priority: 'HIGH'
135 skills: ['collection-setup']
136
137 - mistake: 'TInput not a superset of TOutput with schema transforms'
138 mechanism: 'When schema transforms types (e.g. string -> Date), the input type for mutations must accept the pre-transform type; mismatches cause type errors that are confusing because they reference internal schema types'
139 source: 'docs/guides/schemas.md - TInput must be superset of TOutput'
140 priority: 'HIGH'
141 skills: ['collection-setup']
142
143 - mistake: 'Providing both explicit type parameter and schema'
144 mechanism: 'When a schema is provided, the collection infers types from it; also passing an explicit generic type parameter creates conflicting type constraints'
145 source: 'docs/overview.md - schema type inference note'
146 priority: 'MEDIUM'
147 skills: ['collection-setup']
148
149 - mistake: 'React Native missing crypto.randomUUID polyfill'
150 mechanism: "TanStack DB uses crypto.randomUUID() internally for IDs; React Native doesn't provide this, causing runtime crash; must install react-native-random-uuid"
151 source: 'docs/overview.md - React Native section'
152 priority: 'HIGH'
153 skills: ['collection-setup']
154
155 - mistake: 'Electric txid queried outside mutation transaction'
156 mechanism: "If pg_current_xact_id() is queried in a separate transaction from the actual mutation, the txid won't match the mutation's transaction, causing awaitTxId to stall forever; must query txid INSIDE the same SQL transaction as the mutation"
157 source: 'docs/collections/electric-collection.md - Debugging txid section'
158 priority: 'CRITICAL'
159 skills: ['collection-setup']
160
161 - mistake: 'queryFn returning partial data without merging'
162 mechanism: 'queryFn result is treated as complete state; returning only new/changed items without merging with existing data causes all non-returned items to be deleted from the collection'
163 source: 'docs/collections/query-collection.md - Handling Partial/Incremental Fetches'
164 priority: 'CRITICAL'
165 skills: ['collection-setup']
166
167 - mistake: 'Direct writes overridden by next query sync'
168 mechanism: 'Direct writes (writeInsert, etc.) update the collection immediately, but the next queryFn execution returns the complete server state which overwrites the direct writes; must coordinate staleTime and refetch behavior'
169 source: 'docs/collections/query-collection.md - Direct Writes and Query Sync'
170 priority: 'MEDIUM'
171 skills: ['collection-setup']
172
173 - name: 'Live Queries'
174 slug: 'live-queries'
175 domain: 'live-queries'
176 description: 'Building SQL-like reactive queries across collections'
177 type: 'core'
178 covers:
179 - 'Query builder fluent API (.from, .where, .join, .select, .groupBy, .having, .orderBy, .limit, .offset, .distinct, .findOne)'
180 - 'Comparison operators (eq, ne, gt, gte, lt, lte, like, ilike, inArray, isNull, isUndefined)'
181 - 'Logical operators (and, or, not)'
182 - 'Aggregate functions (count, sum, avg, min, max)'
183 - 'String functions (upper, lower, length, concat, coalesce)'
184 - 'Math functions (add, subtract, multiply, divide)'
185 - 'Join types (inner, left, right, full)'
186 - 'Derived collections (query results are themselves collections)'
187 - 'createLiveQueryCollection (standalone queries outside components)'
188 - 'QueryIR (intermediate representation)'
189 - 'compileQuery (query compilation)'
190 - '$selected namespace for accessing SELECT fields in ORDER BY / HAVING'
191 - 'Predicate push-down (loadSubsetOptions for on-demand sync)'
192 - 'Incremental view maintenance via d2ts (differential dataflow)'
193 tasks:
194 - 'Filter collection items with complex WHERE conditions'
195 - 'Join two collections on a foreign key'
196 - 'Aggregate data with GROUP BY and HAVING'
197 - 'Sort and paginate query results'
198 - 'Create a derived collection from a query for reuse across components'
199 - 'Build a query with computed/projected fields'
200 - 'Use subqueries for complex data access patterns'
201 - 'Move JS array filtering/transformation logic into live queries for better performance'
202 reference_candidates:
203 - topic: 'Query operators'
204 reason: '>20 distinct operators (comparison, logical, aggregate, string, math) with signatures'
205 failure_modes:
206 - mistake: 'Using === instead of eq() in where clauses'
207 mechanism: 'JavaScript === in a where callback returns a boolean, not an expression object; the query silently evaluates to always-false or always-true instead of building the correct filter predicate. Throws InvalidWhereExpressionError.'
208 wrong_pattern: |
209 q.from({ users }).where(({ users }) => users.active === true)
210 correct_pattern: |
211 q.from({ users }).where(({ users }) => eq(users.active, true))
212 source: 'packages/db/src/query/builder/index.ts:375'
213 priority: 'CRITICAL'
214 skills: ['live-queries']
215
216 - mistake: 'Filtering/transforming data in JS instead of using live query operators'
217 mechanism: "AI agents write .filter()/.map()/.reduce() on the data array instead of using the query builder's where/select/groupBy; this throws away incremental maintenance -- the JS code re-runs from scratch on every change, while the query only recomputes the delta"
218 wrong_pattern: |
219 const { data } = useLiveQuery(q => q.from({ todos }))
220 const active = data.filter(t => t.completed === false)
221 correct_pattern: |
222 const { data } = useLiveQuery(q =>
223 q.from({ todos }).where(({ todos }) => eq(todos.completed, false))
224 )
225 source: 'maintainer interview'
226 priority: 'CRITICAL'
227 skills: ['live-queries']
228
229 - mistake: 'Not using the full set of available query operators'
230 mechanism: 'The library has a comprehensive operator set (string functions, math, aggregates, coalesce, etc.) but agents default to basic eq/gt/lt and do the rest in JS; every operator is incrementally maintained and should be preferred over JS equivalents'
231 source: 'maintainer interview'
232 priority: 'HIGH'
233 skills: ['live-queries']
234
235 - mistake: 'Using .distinct() without .select()'
236 mechanism: 'distinct() deduplicates by the entire selected object shape; without select(), the shape is undefined, throwing DistinctRequiresSelectError'
237 source: 'packages/db/src/query/compiler/index.ts:218'
238 priority: 'HIGH'
239 skills: ['live-queries']
240
241 - mistake: 'Using .having() without .groupBy()'
242 mechanism: 'HAVING filters aggregated groups; without GROUP BY there are no groups to filter, throwing HavingRequiresGroupByError'
243 source: 'packages/db/src/query/compiler/index.ts:293'
244 priority: 'HIGH'
245 skills: ['live-queries']
246
247 - mistake: 'Using .limit() or .offset() without .orderBy()'
248 mechanism: 'Without deterministic ordering, limit/offset results are non-deterministic and cannot be incrementally maintained; throws LimitOffsetRequireOrderByError'
249 source: 'packages/db/src/query/compiler/index.ts:356'
250 priority: 'HIGH'
251 skills: ['live-queries']
252
253 - mistake: 'Join condition using operator other than eq()'
254 mechanism: 'The D2 differential dataflow join operator only supports equality joins; using gt(), like(), etc. throws JoinConditionMustBeEqualityError'
255 source: 'packages/db/src/query/builder/index.ts:216'
256 priority: 'HIGH'
257 skills: ['live-queries']
258
259 - mistake: 'Passing source directly instead of as {alias: collection}'
260 mechanism: 'from() and join() require sources wrapped as {alias: collection}; passing the collection directly throws InvalidSourceTypeError'
261 wrong_pattern: |
262 q.from(usersCollection)
263 correct_pattern: |
264 q.from({ users: usersCollection })
265 source: 'packages/db/src/query/builder/index.ts:79-96'
266 priority: 'MEDIUM'
267 skills: ['live-queries']
268
269 - name: 'Framework Integration'
270 slug: 'framework-integration'
271 domain: 'framework-integration'
272 description: 'Binding live queries to UI framework components'
273 type: 'framework'
274 covers:
275 - 'React: useLiveQuery, useLiveSuspenseQuery, useLiveInfiniteQuery, usePacedMutations'
276 - 'Vue: useLiveQuery composable with computed refs'
277 - 'Svelte: useLiveQuery with Svelte 5 runes'
278 - 'Solid: useLiveQuery with fine-grained reactivity'
279 - 'Angular: injectLiveQuery with signals'
280 - 'Dependency arrays for reactive query parameters'
281 - 'React Suspense integration with Error Boundaries'
282 - 'Infinite query pagination (cursor-based)'
283 - 'Return shape: { data, state, collection, status, isLoading, isReady, isError }'
284 tasks:
285 - 'Bind a live query to a React component with useLiveQuery'
286 - 'Use React Suspense for loading states with useLiveSuspenseQuery'
287 - 'Implement infinite scroll with useLiveInfiniteQuery'
288 - 'Pass reactive parameters to queries in Vue (refs) / Angular (signals) / Solid (signals)'
289 - 'Set up dependency arrays for dynamic query parameters'
290 subsystems:
291 - name: 'React'
292 package: '@tanstack/react-db'
293 config_surface: 'useLiveQuery, useLiveSuspenseQuery, useLiveInfiniteQuery, usePacedMutations'
294 - name: 'Vue'
295 package: '@tanstack/vue-db'
296 config_surface: 'useLiveQuery composable with MaybeRefOrGetter'
297 - name: 'Svelte'
298 package: '@tanstack/svelte-db'
299 config_surface: 'useLiveQuery with Svelte 5 runes ($state)'
300 - name: 'Solid'
301 package: '@tanstack/solid-db'
302 config_surface: 'useLiveQuery with Accessor/createSignal'
303 - name: 'Angular'
304 package: '@tanstack/angular-db'
305 config_surface: 'injectLiveQuery with Signal, inject(DestroyRef)'
306 failure_modes:
307 - mistake: 'Missing external values in useLiveQuery dependency array'
308 mechanism: "When query uses external state (props, local state) not included in deps array, the query won't re-run when those values change, showing stale results"
309 wrong_pattern: |
310 const { data } = useLiveQuery(q =>
311 q.from({ todos }).where(({ todos }) => eq(todos.userId, userId))
312 ) // userId not in deps
313 correct_pattern: |
314 const { data } = useLiveQuery(q =>
315 q.from({ todos }).where(({ todos }) => eq(todos.userId, userId)),
316 [userId]
317 )
318 source: 'docs/framework/react/overview.md - dependency array section'
319 priority: 'CRITICAL'
320 skills: ['framework-integration']
321
322 - mistake: 'Reading Solid signals outside the query function'
323 mechanism: "Solid's reactivity tracks signal reads inside the query function; reading signals before passing to useLiveQuery means changes aren't tracked and query won't re-run"
324 source: 'docs/framework/solid/overview.md - fine-grained reactivity section'
325 priority: 'HIGH'
326 skills: ['framework-integration']
327
328 - mistake: 'Using useLiveSuspenseQuery without Error Boundary'
329 mechanism: 'Suspense query throws errors during rendering; without an Error Boundary wrapping the component, the entire app crashes instead of showing a fallback'
330 source: 'docs/guides/live-queries.md - React Suspense section'
331 priority: 'HIGH'
332 skills: ['framework-integration']
333
334 - mistake: 'Passing non-function deps in Svelte instead of getter functions'
335 mechanism: 'In Svelte 5, props and derived values should be wrapped in getter functions in the dependency array to maintain reactivity; passing values directly captures them at creation time'
336 source: 'docs/framework/svelte/overview.md - Props in dependencies'
337 priority: 'MEDIUM'
338 skills: ['framework-integration']
339 compositions:
340 - library: 'meta-framework'
341 skill: 'meta-framework'
342
343 - name: 'Mutations & Optimistic State'
344 slug: 'mutations-optimistic'
345 domain: 'mutations-optimistic'
346 description: 'Writing data to collections with instant optimistic feedback'
347 type: 'core'
348 covers:
349 - 'collection.insert(), collection.update(), collection.delete()'
350 - 'createOptimisticAction (custom mutation actions)'
351 - 'createPacedMutations (debounced/throttled mutations)'
352 - 'createTransaction (manual transaction control)'
353 - 'getActiveTransaction (ambient transaction context)'
354 - 'Transaction lifecycle (pending -> persisting -> completed | failed)'
355 - 'Transaction stacking (concurrent transactions build on each other)'
356 - 'Mutation merging (insert+update -> insert, insert+delete -> null, etc.)'
357 - 'onInsert, onUpdate, onDelete handlers'
358 - 'Optimistic vs non-optimistic updates (optimistic: false)'
359 - 'Automatic rollback on handler error'
360 - 'Change tracking proxy (draft updates via Immer-like API)'
361 - 'PendingMutation type (original, modified, changes, globalKey)'
362 - 'Transaction.isPersisted promise'
363 - 'Temporary ID handling'
364 - 'TanStack Pacer integration for sequential execution'
365 tasks:
366 - 'Insert a new item with optimistic UI update'
367 - 'Update an item using the draft proxy pattern'
368 - 'Delete items with automatic rollback on server error'
369 - 'Create a custom optimistic action for complex mutations'
370 - 'Use paced mutations for real-time text editing'
371 - 'Batch multiple mutations into a single transaction'
372 - 'Handle temporary IDs that get replaced by server-generated IDs'
373 - 'Use pacer for sequential transaction execution to avoid conflicts'
374 failure_modes:
375 - mistake: 'Passing a new object to update() instead of mutating the draft'
376 mechanism: "collection.update(id, {...item, title: 'new'}) is wrong; the API uses an Immer-style draft proxy: collection.update(id, (draft) => { draft.title = 'new' }). Passing an object instead of a callback silently fails or throws a confusing error."
377 wrong_pattern: |
378 collection.update(id, { ...item, title: 'new' })
379 correct_pattern: |
380 collection.update(id, (draft) => { draft.title = 'new' })
381 source: 'maintainer interview'
382 priority: 'CRITICAL'
383 skills: ['mutations-optimistic']
384
385 - mistake: 'Hallucinating mutation API signatures'
386 mechanism: 'AI agents generate plausible but wrong mutation code -- inventing handler signatures, confusing createOptimisticAction with createTransaction, missing the ambient transaction pattern, or wrong PendingMutation property names (e.g. transaction.mutations[0].changes vs .data)'
387 source: 'maintainer interview'
388 priority: 'CRITICAL'
389 skills: ['mutations-optimistic']
390
391 - mistake: 'onMutate callback returning a Promise'
392 mechanism: 'onMutate in createOptimisticAction must be synchronous because optimistic state needs to be applied immediately in the current tick; returning a Promise throws OnMutateMustBeSynchronousError'
393 wrong_pattern: |
394 createOptimisticAction({
395 onMutate: async (text) => { collection.insert({ id: await generateId(), text }) },
396 mutationFn: async (text, { transaction }) => { ... }
397 })
398 correct_pattern: |
399 createOptimisticAction({
400 onMutate: (text) => { collection.insert({ id: crypto.randomUUID(), text }) },
401 mutationFn: async (text, { transaction }) => { ... }
402 })
403 source: 'packages/db/src/optimistic-action.ts:75'
404 priority: 'CRITICAL'
405 skills: ['mutations-optimistic']
406
407 - mistake: 'Calling insert/update/delete without handler or ambient transaction'
408 mechanism: 'Collection mutations require either an onInsert/onUpdate/onDelete handler or an ambient transaction from createTransaction; without either, throws MissingInsertHandlerError (or Update/Delete variant)'
409 source: 'packages/db/src/collection/mutations.ts:166'
410 priority: 'CRITICAL'
411 skills: ['mutations-optimistic']
412
413 - mistake: 'Calling .mutate() after transaction is no longer pending'
414 mechanism: "Transactions can only accept new mutations while in 'pending' state; calling mutate() after commit() or rollback() throws TransactionNotPendingMutateError"
415 source: 'packages/db/src/transactions.ts:289'
416 priority: 'HIGH'
417 skills: ['mutations-optimistic']
418
419 - mistake: "Attempting to change an item's primary key via update"
420 mechanism: 'The update proxy detects key changes and throws KeyUpdateNotAllowedError; primary keys are immutable once set'
421 source: 'packages/db/src/collection/mutations.ts:352'
422 priority: 'HIGH'
423 skills: ['mutations-optimistic']
424
425 - mistake: 'Inserting item with duplicate key'
426 mechanism: 'If an item with the same key already exists in the collection (synced or optimistic), throws DuplicateKeyError; common when using client-generated IDs without checking'
427 source: 'packages/db/src/collection/mutations.ts:181'
428 priority: 'HIGH'
429 skills: ['mutations-optimistic']
430
431 - mistake: 'Not awaiting refetch after mutation in query collection handler'
432 mechanism: "In query collection onInsert/onUpdate/onDelete handlers, the optimistic state is only held until the handler resolves; if you don't await the refetch or sync back, the optimistic state is dropped before new server state arrives, causing a flash of missing data"
433 wrong_pattern: |
434 onInsert: async ({ transaction }) => {
435 await api.createTodo(transaction.mutations[0].modified)
436 // missing: await collection.utils.refetch()
437 }
438 correct_pattern: |
439 onInsert: async ({ transaction }) => {
440 await api.createTodo(transaction.mutations[0].modified)
441 await collection.utils.refetch()
442 }
443 source: 'docs/overview.md - optimistic state lifecycle'
444 priority: 'HIGH'
445 skills: ['mutations-optimistic']
446
447 - name: 'Meta-Framework Integration'
448 slug: 'meta-framework'
449 domain: 'meta-framework'
450 description: 'Client-side preloading of collections in route loaders for meta-frameworks'
451 type: 'composition'
452 covers:
453 - 'collection.preload() in route loaders'
454 - 'collection.stateWhenReady() and toArrayWhenReady()'
455 - 'collection.onFirstReady(callback)'
456 - 'Pre-creating createLiveQueryCollection in loaders'
457 - 'Setting ssr: false on routes using collections'
458 - 'TanStack Start / TanStack Router loader patterns'
459 - 'Coordinating collection lifecycle with route transitions'
460 - 'Passing pre-loaded collections to components via loader data'
461 tasks:
462 - 'Preload a collection in a TanStack Router route loader'
463 - 'Pre-create a live query collection in a loader and pass to component'
464 - 'Configure ssr: false on routes that use TanStack DB collections'
465 - 'Coordinate multiple collection preloads in a single route loader'
466 - 'Handle route transitions when collections are still loading'
467 failure_modes:
468 - mistake: 'Not preloading collections in route loaders'
469 mechanism: 'Without preload() in the loader, the collection starts syncing only when the component mounts; this causes a loading flash even though the router could have started the sync during navigation'
470 wrong_pattern: |
471 export const Route = createFileRoute('/todos')({
472 component: TodoList,
473 // no loader -- collection loads on mount
474 })
475 correct_pattern: |
476 export const Route = createFileRoute('/todos')({
477 component: TodoList,
478 ssr: false,
479 loader: async () => {
480 await todosCollection.preload()
481 },
482 })
483 source: 'examples/react/projects/src/routes'
484 priority: 'HIGH'
485 skills: ['meta-framework']
486
487 - mistake: 'Not setting ssr: false on routes using collections'
488 mechanism: 'Collections are client-side only (no SSR support yet); rendering a route with collections on the server attempts to access browser-only APIs, causing crashes or hydration mismatches'
489 wrong_pattern: |
490 export const Route = createFileRoute('/todos')({
491 component: TodoList,
492 loader: async () => {
493 await todosCollection.preload()
494 },
495 })
496 correct_pattern: |
497 export const Route = createFileRoute('/todos')({
498 component: TodoList,
499 ssr: false,
500 loader: async () => {
501 await todosCollection.preload()
502 },
503 })
504 source: 'examples/react/projects/src/start.tsx - defaultSsr: false'
505 priority: 'CRITICAL'
506 skills: ['meta-framework']
507
508 - mistake: 'Creating new collection instances inside loaders on every navigation'
509 mechanism: 'createLiveQueryCollection should be called once and reused; creating new instances on each navigation leaks D2 graph nodes and subscriptions'
510 source: 'docs/guides/live-queries.md - standalone queries'
511 priority: 'HIGH'
512 skills: ['meta-framework']
513 compositions:
514 - library: '@tanstack/react-router'
515 skill: 'framework-integration'
516
517 - name: 'Custom Adapter Authoring'
518 slug: 'custom-adapter'
519 domain: 'custom-adapter'
520 description: 'Building custom collection adapters for new backends'
521 type: 'core'
522 covers:
523 - 'SyncConfig interface (sync, getSyncMetadata, rowUpdateMode)'
524 - 'Sync primitives (begin, write, commit, markReady, truncate)'
525 - 'ChangeMessage format (insert, update, delete)'
526 - 'loadSubset for on-demand sync mode'
527 - 'LoadSubsetOptions (where, orderBy, limit, cursor)'
528 - 'Expression parsing helpers (parseWhereExpression, parseOrderByExpression, extractSimpleComparisons)'
529 - 'Collection options creator pattern'
530 - 'Subscription lifecycle and cleanup'
531 tasks:
532 - 'Build a custom collection adapter for a new backend'
533 - 'Implement loadSubset for on-demand predicate push-down'
534 - 'Use expression parsing helpers to translate query predicates to API params'
535 - 'Handle the sync lifecycle correctly (begin/write/commit/markReady)'
536 failure_modes:
537 - mistake: 'Not calling markReady() in custom sync implementation'
538 mechanism: "markReady() transitions the collection from 'loading' to 'ready' status; forgetting to call it means live queries never resolve and useLiveSuspenseQuery hangs forever in Suspense"
539 wrong_pattern: |
540 sync: ({ begin, write, commit }) => {
541 fetchData().then(items => {
542 begin()
543 items.forEach(item => write({ type: 'insert', value: item }))
544 commit()
545 // forgot markReady()!
546 })
547 }
548 correct_pattern: |
549 sync: ({ begin, write, commit, markReady }) => {
550 fetchData().then(items => {
551 begin()
552 items.forEach(item => write({ type: 'insert', value: item }))
553 commit()
554 markReady()
555 })
556 }
557 source: 'docs/guides/collection-options-creator.md - markReady section'
558 priority: 'CRITICAL'
559 skills: ['custom-adapter']
560
561 - mistake: 'Race condition between initial sync and event subscription'
562 mechanism: "If live change events aren't subscribed BEFORE the initial data fetch, changes that occur during the fetch are lost; the sync implementation must start listening before fetching"
563 wrong_pattern: |
564 sync: ({ begin, write, commit, markReady }) => {
565 // BAD: fetch first, then subscribe
566 const data = await fetchAll()
567 writeAll(data)
568 subscribe(onChange) // missed changes during fetch!
569 }
570 correct_pattern: |
571 sync: ({ begin, write, commit, markReady }) => {
572 // GOOD: subscribe first, then fetch
573 subscribe(onChange)
574 const data = await fetchAll()
575 writeAll(data)
576 }
577 source: 'docs/guides/collection-options-creator.md - Race condition prevention'
578 priority: 'HIGH'
579 skills: ['custom-adapter']
580
581 - mistake: 'write() called without begin() in sync implementation'
582 mechanism: 'Sync data must be written within a transaction (begin -> write -> commit); calling write() without begin() throws NoPendingSyncTransactionWriteError'
583 source: 'packages/db/src/collection/sync.ts:110'
584 priority: 'HIGH'
585 skills: ['custom-adapter']
586
587 - name: 'Offline Transactions'
588 slug: 'offline'
589 domain: 'offline'
590 description: 'Offline-first transaction queueing with persistence and retry'
591 type: 'composition'
592 covers:
593 - 'OfflineExecutor / startOfflineExecutor'
594 - 'OfflineConfig (collections, mutationFns, storage, maxConcurrency)'
595 - 'Storage adapters (IndexedDBAdapter, LocalStorageAdapter)'
596 - 'Retry policies (DefaultRetryPolicy, BackoffCalculator, NonRetriableError)'
597 - 'Leader election (WebLocksLeader, BroadcastChannelLeader)'
598 - 'Online detection (WebOnlineDetector)'
599 - 'OutboxManager (transaction queue)'
600 - 'KeyScheduler (prevents concurrent mutations on same key)'
601 - 'TransactionSerializer (persistence)'
602 - 'React Native support (@react-native-community/netinfo)'
603 tasks:
604 - 'Set up offline-first transactions with @tanstack/offline-transactions'
605 - 'Configure IndexedDB storage for transaction persistence'
606 - 'Handle multi-tab coordination with leader election'
607 - 'Implement custom retry logic with NonRetriableError'
608 - 'Set up offline support for React Native with NetInfo'
609 failure_modes:
610 - mistake: 'Using offline transactions when not needed'
611 mechanism: 'Offline is inherently complex; @tanstack/offline-transactions adds storage, leader election, and retry overhead. Only adopt when true offline support is required. PowerSync/RxDB handle their own local persistence, which is a different concern.'
612 source: 'maintainer interview'
613 priority: 'HIGH'
614 skills: ['offline']
615
616 - mistake: 'Not handling NonRetriableError for permanent failures'
617 mechanism: 'By default, failed transactions retry with exponential backoff; for permanent failures (e.g. 400 Bad Request), throw NonRetriableError to skip retry and move the transaction to a dead-letter state'
618 source: 'packages/offline-transactions/src/retry.ts'
619 priority: 'HIGH'
620 skills: ['offline']
621
622 - mistake: 'Multiple tabs executing the same queued transaction'
623 mechanism: 'Without leader election, each tab runs its own OfflineExecutor and processes the outbox independently, causing duplicate mutations; must configure WebLocksLeader or BroadcastChannelLeader'
624 source: 'packages/offline-transactions/src/leader/'
625 priority: 'CRITICAL'
626 skills: ['offline']
627
628tensions:
629 - name: 'Simplicity vs. correctness in sync'
630 skills: ['collection-setup', 'custom-adapter']
631 description: 'Getting-started simplicity (localOnlyCollectionOptions, eager sync) conflicts with production correctness (on-demand sync, proper adapter selection, race condition prevention)'
632 implication: 'Agents use localOnly or eager mode for everything; production apps need adapter-specific patterns and on-demand sync for large datasets'
633
634 - name: 'Optimistic speed vs. data consistency'
635 skills: ['mutations-optimistic', 'collection-setup']
636 description: 'Instant optimistic updates create a window where client state diverges from server state; resolving conflicts on rollback can lose user work'
637 implication: 'Agents apply optimistic updates without considering rollback UX or awaiting refetch in mutation handlers'
638
639 - name: 'Query expressiveness vs. IVM constraints'
640 skills: ['live-queries', 'framework-integration']
641 description: "The query builder looks like SQL but has constraints (equality joins only, orderBy required for limit, no distinct without select) that SQL doesn't have"
642 implication: 'Agents write SQL-style queries that violate IVM constraints, producing confusing errors'
643
644 - name: 'Offline complexity vs. app simplicity'
645 skills: ['offline', 'mutations-optimistic']
646 description: "Offline transaction support adds storage, leader election, and retry complexity; most apps don't need it but agents may recommend it prematurely"
647 implication: 'Agents add @tanstack/offline-transactions to apps that only need basic optimistic mutations'
648
649cross_references:
650 - from: 'framework-integration'
651 to: 'meta-framework'
652 reason: 'Framework hooks render data; meta-framework loaders preload it. Developers need both for production apps with routing.'
653
654 - from: 'meta-framework'
655 to: 'framework-integration'
656 reason: 'Preloaded collections are consumed by framework hooks; understanding the hook API informs what to preload.'
657
658 - from: 'collection-setup'
659 to: 'mutations-optimistic'
660 reason: 'Collection mutation handlers (onInsert/onUpdate/onDelete) are configured at setup time but execute during mutations; understanding both is required for working writes.'
661
662 - from: 'mutations-optimistic'
663 to: 'collection-setup'
664 reason: 'Mutation handler signatures and behavior depend on which adapter is used (e.g. Electric txid return, Query refetch).'
665
666 - from: 'live-queries'
667 to: 'collection-setup'
668 reason: 'Live queries reference collections by alias; understanding collection types and sync modes affects query behavior (e.g. on-demand predicate push-down).'
669
670 - from: 'custom-adapter'
671 to: 'collection-setup'
672 reason: 'Custom adapters produce the same CollectionConfig shape that built-in adapters use; understanding the config contract is essential.'
673
674 - from: 'offline'
675 to: 'mutations-optimistic'
676 reason: 'Offline transactions wrap the same transaction/mutation model; understanding createTransaction and PendingMutation is prerequisite.'
677
678gaps:
679 - skill: 'meta-framework'
680 question: 'What are the specific patterns for non-TanStack-Start frameworks (Next.js App Router, Remix loaders, Nuxt middleware, SvelteKit load functions)?'
681 context: 'Only TanStack Start/Router patterns are documented in examples; other frameworks need guidance'
682 status: 'open'
683
684 - skill: 'collection-setup'
685 question: 'What is the recommended pattern for collection cleanup/disposal in single-page apps with route-based code splitting?'
686 context: "gcTime defaults to 5 minutes, but docs don't clearly explain when/how collections are garbage collected or what triggers cleanup"
687 status: 'open'
688
689 - skill: 'live-queries'
690 question: 'Are there performance cliffs with live queries? At what complexity/data size do queries degrade?'
691 context: "Docs claim sub-millisecond for 100k items, but don't discuss limits (e.g., 5-way joins, deeply nested aggregations)"
692 status: 'open'
693
694 - skill: 'mutations-optimistic'
695 question: 'What is the recommended pattern for handling temporary IDs that get replaced by server-generated IDs?'
696 context: "The mutations guide mentions temporary IDs but the pattern for mapping client IDs to server IDs during sync isn't well documented"
697 status: 'open'
698
699 - skill: 'meta-framework'
700 question: 'What are the specific patterns for TanStack Router integration with collection loading/prefetching?'
701 context: 'Maintainer reports this is a major composition pain point; agents struggle with the loading/prefetching pattern'
702 status: 'open'
703
704 - skill: 'offline'
705 question: 'What happens to in-flight transactions when the browser goes offline mid-persist?'
706 context: "The offline executor package handles queuing, but the interaction with the main transaction lifecycle isn't documented"
707 status: 'open'