tanstack/db/collection-setup
Claude Code and agent skill by tanstack/db
- community
Checking that the SKILL.md file is still in the repository.
Creating typed collections with createCollection. Adapter selection: queryCollectionOptions (REST/TanStack Query), electricCollectionOptions (ElectricSQL real-time sync), powerSyncCollectionOptions (PowerSync SQLite), rxdbCollectionOptions (RxDB), trailBaseCollectionOptions (TrailBase), localOnlyCollectionOptions, localStorageCollectionOptions, indexedDBCollectionOptions. CollectionConfig options: getKey, schema, sync, gcTime, autoIndex (default off), defaultIndexType, syncMode (eager/on-demand, plus progressive for Electric). StandardSchema validation with Zod/Valibot/ArkType. Collection lifecycle (idle/loading/ready/error). Adapter-specific sync patterns including Electric txid tracking, Query direct writes, Query initial data and scoped factories, and PowerSync query-driven sync with onLoad/onLoadSubset hooks.
Install
npx vskill@latest install tanstack/db/collection-setupSKILL.md
The same SKILL.md was published earlier as tanstack/db/collection-setup.
This skill builds on db-core. Read it first for the overall mental model.
Collection Setup & Schema
Setup
Choosing an Adapter
| Backend | Adapter | Package | |
|---|---|---|---|
| REST API / TanStack Query | queryCollectionOptions | @tanstack/query-db-collection | |
| ElectricSQL (real-time Postgres) | electricCollectionOptions | @tanstack/electric-db-collection | |
| PowerSync (SQLite offline) | powerSyncCollectionOptions | @tanstack/powersync-db-collection | |
| RxDB (reactive database) | rxdbCollectionOptions | @tanstack/rxdb-db-collection | |
| TrailBase (event streaming) | trailBaseCollectionOptions | @tanstack/trailbase-db-collection | |
| No backend (UI state) | localOnlyCollectionOptions | @tanstack/db | |
| Browser localStorage | localStorageCollectionOptions | @tanstack/db | |
| Browser IndexedDB | indexedDBCollectionOptions | @tanstack/db |
If the user specifies a backend (e.g. Electric, PowerSync), use that adapter directly. Only use localOnlyCollectionOptions when there is no backend yet — the collection API is uniform, so swapping to a real adapter later only changes the options creator.
Sync Modes
| Mode | Best for | Data size | |
|---|---|---|---|
eager | Mostly-static datasets | <10k rows | |
on-demand | Search, catalogs, large tables | >50k rows | |
progressive | Collaborative apps needing instant first paint (Electric only) | Any |
Calling collection.preload() on an on-demand collection is a no-op. Create the live query for the required subset and call liveQuery.preload() instead.
For Query Collection request cancellation, cleanup boundaries, and shared QueryClient behavior, read the Query adapter reference.
Indexing
Indexing is opt-in. The autoIndex option defaults to "off". To enable automatic indexing, set autoIndex: "eager" and provide a defaultIndexType:
Without defaultIndexType, setting autoIndex: "eager" throws a CollectionConfigurationError. You can also create indexes manually with collection.createIndex() and remove them with collection.removeIndex().
Core Patterns
Local-only collection for prototyping
Schema with type transformations
Use z.union([z.string(), z.date()]) for transformed fields — this ensures TInput is a superset of TOutput so that update() works correctly with the draft proxy.
ElectricSQL with txid tracking
Always use a schema with Electric — without one, the collection types as Record<string, unknown>.
The handler waits for Electric to stream the txid before it completes, keeping optimistic state visible until then. See the Electric adapter reference for the full dual-path pattern (schema + parser).
Common Mistakes
CRITICAL queryFn returning empty array deletes all data
Wrong:
Correct:
In eager mode, queryFn is complete collection state. Returning [] means "the server has no items" and removes all rows. In on-demand mode, a result is complete only for that exact subset/Query key; an empty result releases that subset's ownership, while overlapping subsets can keep shared rows.
Source: docs/collections/query-collection.md
CRITICAL Not using the correct adapter for your backend
Wrong:
Correct:
Each backend has a dedicated adapter that handles sync, mutation handlers, and utilities. Using localOnlyCollectionOptions or bare createCollection for a real backend bypasses all of this.
Source: docs/overview.md
CRITICAL Electric txid queried outside mutation transaction
Wrong:
Correct:
pg_current_xact_id() must be queried inside the same SQL transaction as the mutation. Otherwise the txid doesn't match and awaitTxId times out (default 5 seconds).
Source: docs/collections/electric-collection.md
CRITICAL queryFn returning partial data without merging
Wrong:
Correct:
An eager queryFn result replaces all collection data. For incremental eager fetches, merge with existing data. In on-demand mode, return the complete state for the requested subset instead.
Source: docs/collections/query-collection.md
HIGH Using async schema validation
Wrong:
Correct:
Schema validation must be synchronous. Async validation throws SchemaMustBeSynchronousError at mutation time.
Source: packages/db/src/collection/mutations.ts:101
HIGH getKey returning undefined for some items
Wrong:
Correct:
getKey must return a defined value for every item. Throws UndefinedKeyError otherwise.
Source: packages/db/src/collection/mutations.ts:148
HIGH TInput not a superset of TOutput with schema transforms
Wrong:
Correct:
When a schema transforms types, TInput must accept both the pre-transform and post-transform types for update() to work with the draft proxy.
Source: docs/guides/schemas.md
HIGH Runtime has no secure random number generator
TanStack DB's safeRandomUUID() uses crypto.randomUUID() when available and falls back to crypto.getRandomValues(), including on non-secure HTTP origins. Add a Web Crypto polyfill only in runtimes, including some React Native versions, that provide neither API.
Source: packages/db/src/utils/uuid.ts, packages/db/tests/uuid.test.ts
MEDIUM Providing both explicit type parameter and schema
Wrong:
Correct:
When a schema is provided, the collection infers types from it. An explicit generic creates conflicting type constraints.
Source: docs/overview.md
MEDIUM Direct writes overridden by next query sync
Wrong:
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 93 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingpackages/db/skills/db-core/collection-setup/SKILL.md
Popularity
- Repository stars
- 3,880
- Repository forks
- 258
- 7-day trend score
- 41
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/tanstack/db/collection-setup)