### Install Dependencies and Run Application
Source: https://github.com/tanstack/db/blob/main/examples/react/projects/README.md
Commands to install project dependencies and start the development server. It also includes instructions for running database migrations from a separate terminal.
```bash
npm install
npm run dev
# From a separate terminal
npm run migrate
```
--------------------------------
### Install Dependencies
Source: https://github.com/tanstack/db/blob/main/examples/react/todo/README.md
Run this command to install project dependencies.
```bash
pnpm install
```
--------------------------------
### TanStack DB: Live Queries for Filtering and Sorting
Source: https://github.com/tanstack/db/blob/main/docs/quick-start.md
This example shows how to use `useLiveQuery` to fetch and display data reactively. It includes examples of basic filtering (e.g., incomplete todos) and sorting (by creation date), as well as data transformation to create a summarized view of todos.
```tsx
function TodoList() {
// Basic filtering and sorting
const { data: incompleteTodos } = useLiveQuery((q) =>
q.from({ todo: todoCollection })
.where(({ todo }) => eq(todo.completed, false))
.orderBy(({ todo }) => todo.createdAt, 'desc')
)
// Transform the data
const { data: todoSummary } = useLiveQuery((q) =>
q.from({ todo: todoCollection })
.select(({ todo }) => ({
id: todo.id,
summary: `${todo.text} (${todo.completed ? 'done' : 'pending'})`,
priority: todo.priority || 'normal'
}))
)
return
{/* Render todos */}
}
```
--------------------------------
### Start Development Server
Source: https://github.com/tanstack/db/blob/main/examples/react/todo/README.md
Starts the dev server and Docker containers for Postgres, Electric, and TrailBase.
```bash
pnpm dev
```
--------------------------------
### TanStack DB: Installation
Source: https://github.com/tanstack/db/blob/main/docs/quick-start.md
This command installs the necessary TanStack DB and TanStack Query DB Collection packages using npm. These packages are essential for setting up reactive data collections and integrating them with TanStack Query.
```bash
npm install @tanstack/react-db @tanstack/query-db-collection
```
--------------------------------
### Initialize persisted collection
Source: https://github.com/tanstack/db/blob/main/packages/tauri-db-sqlite-persistence/README.md
Quick start example for setting up a persisted collection with SQLite.
```typescript
import Database from '@tauri-apps/plugin-sql'
import { createCollection } from '@tanstack/db'
import {
createTauriSQLitePersistence,
persistedCollectionOptions,
} from '@tanstack/tauri-db-sqlite-persistence'
type Todo = {
id: string
title: string
completed: boolean
}
const database = await Database.load(`sqlite:tanstack-db.sqlite`)
const persistence = createTauriSQLitePersistence({
database,
})
export const todosCollection = createCollection(
persistedCollectionOptions({
id: `todos`,
getKey: (todo) => todo.id,
persistence,
schemaVersion: 1,
}),
)
```
--------------------------------
### useLiveQuery Examples
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/reference/functions/useLiveQuery.md
Illustrative examples demonstrating various use cases of the useLiveQuery hook.
```APIDOC
## Examples
### Basic query with object syntax
```ts
// Basic query with object syntax
const { data, isLoading } = useLiveQuery((q) =>
q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.completed, false))
.select(({ todos }) => ({ id: todos.id, text: todos.text }))
)
```
### Single result query
```ts
// Single result query
const { data } = useLiveQuery(
(q) => q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.id, 1))
.findOne()
)
```
### With dependencies that trigger re-execution
```ts
// With dependencies that trigger re-execution
const { data, state } = useLiveQuery(
(q) => q.from({ todos: todosCollection })
.where(({ todos }) => gt(todos.priority, minPriority)),
[minPriority] // Re-run when minPriority changes
)
```
### Join pattern
```ts
// Join pattern
const { data } = useLiveQuery((q) =>
q.from({ issues: issueCollection })
.join({ persons: personCollection }, ({ issues, persons }) =>
eq(issues.userId, persons.id)
)
.select(({ issues, persons }) => ({
id: issues.id,
title: issues.title,
userName: persons.name
}))
)
```
### Handle loading and error states
```ts
// Handle loading and error states
const { data, isLoading, isError, status } = useLiveQuery((q) =>
q.from({ todos: todoCollection })
)
if (isLoading) return Loading...
if (isError) return Error: {status}
return (
{data.map(todo => - {todo.text}
)}
)
```
```
--------------------------------
### Setup useLiveQuery in SolidJS
Source: https://github.com/tanstack/db/blob/main/packages/solid-db/skills/solid-db/SKILL.md
Demonstrates basic setup of the useLiveQuery hook for fetching and displaying a list of incomplete todos. Requires @tanstack/solid-db and SolidJS components.
```tsx
import { useLiveQuery, eq, not } from '@tanstack/solid-db'
import { For, Show, Suspense } from 'solid-js'
function TodoList() {
const todosQuery = useLiveQuery((q) =>
q
.from({ todo: todoCollection })
.where(({ todo }) => not(todo.completed))
.orderBy(({ todo }) => todo.created_at, 'asc'),
)
return (
Loading...}>
)
}
```
--------------------------------
### GraphQL Query Example
Source: https://github.com/tanstack/db/blob/main/docs/collections/query-collection.md
An example demonstrating how to fetch products from a GraphQL API using parsed query options.
```APIDOC
## GraphQL Query Example
This example shows how to use the `parseWhereExpression` and `parseOrderByExpression` helpers to construct a GraphQL query for fetching products.
### Code
```typescript
queryFn: async (ctx) => {
const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
// Convert to a GraphQL where clause format
const whereClause = parseWhereExpression(where, {
handlers: {
eq: (field, value) => ({
[field.join('_')]: { _eq: value }
}),
lt: (field, value) => ({
[field.join('_')]: { _lt: value }
}),
and: (...conditions) => ({ _and: conditions }),
or: (...conditions) => ({ _or: conditions }),
}
})
// Convert to a GraphQL order_by format
const sorts = parseOrderByExpression(orderBy)
const orderByClause = sorts.map(s => ({
[s.field.join('_')]: s.direction
}))
const { data } = await graphqlClient.query({
query: gql`
query GetProducts($where: product_bool_exp, $orderBy: [product_order_by!], $limit: Int) {
product(where: $where, order_by: $orderBy, limit: $limit) {
id
name
category
price
}
}
`,
variables: {
where: whereClause,
orderBy: orderByClause,
limit
}
})
return data.product
}
```
```
--------------------------------
### Install dependencies
Source: https://github.com/tanstack/db/blob/main/packages/tauri-db-sqlite-persistence/README.md
Install the required packages for SQLite persistence in your project.
```bash
pnpm add @tanstack/tauri-db-sqlite-persistence @tauri-apps/plugin-sql
```
--------------------------------
### preload()
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/CollectionImpl.md
Starts the collection synchronization process if it hasn't started yet.
```APIDOC
## preload()
### Description
Preload the collection data by starting sync if not already started. Multiple concurrent calls will share the same promise.
### Returns
- **Promise**
```
--------------------------------
### Setup useLiveQuery in Vue
Source: https://github.com/tanstack/db/blob/main/packages/vue-db/skills/vue-db/SKILL.md
Demonstrates basic setup of the useLiveQuery hook to fetch and display a list of todos, filtering out completed ones. Requires @tanstack/vue-db and a pre-defined todoCollection.
```vue
Loading...
```
--------------------------------
### Setup Todo List Component with injectLiveQuery
Source: https://github.com/tanstack/db/blob/main/packages/angular-db/skills/angular-db/SKILL.md
Demonstrates setting up a component to display a list of incomplete todos using injectLiveQuery. It utilizes Angular 17+ control flow and signal inputs for reactive data display. Ensure you have @tanstack/angular-db installed and imported.
```typescript
import { Component } from '@angular/core'
import { injectLiveQuery, eq, not } from '@tanstack/angular-db'
@Component({
selector: 'app-todo-list',
standalone: true,
template: `
@if (query.isLoading()) {
Loading...
} @else {
@for (todo of query.data(); track todo.id) {
- {{ todo.text }}
}
}
`,
})
export class TodoListComponent {
query = injectLiveQuery((q) =>
q
.from({ todos: todosCollection })
.where(({ todos }) => not(todos.completed))
.orderBy(({ todos }) => todos.created_at, 'asc'),
)
}
```
--------------------------------
### Usage Examples for createLiveQueryCollection
Source: https://github.com/tanstack/db/blob/main/docs/reference/functions/createLiveQueryCollection.md
Examples showing minimal usage with a query function and full configuration with custom options.
```typescript
// Minimal usage - just pass a query function
const activeUsers = createLiveQueryCollection(
(q) => q
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true))
.select(({ user }) => ({ id: user.id, name: user.name }))
)
// Full configuration with custom options
const searchResults = createLiveQueryCollection({
id: "search-results", // Custom ID (auto-generated if omitted)
query: (q) => q
.from({ post: postsCollection })
.where(({ post }) => like(post.title, `%${searchTerm}%`))
.select(({ post }) => ({
id: post.id,
title: post.title,
excerpt: post.excerpt,
})),
getKey: (item) => item.id, // Custom key function (uses stream key if omitted)
utils: {
updateSearchTerm: (newTerm: string) => {
// Custom utility functions
}
}
})
```
--------------------------------
### Install PowerSync Dependencies
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/powersync-adapter.md
Install the necessary packages for PowerSync integration with TanStack DB and SQLite.
```bash
pnpm add @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite
```
--------------------------------
### useLiveInfiniteQuery Hook Example
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/overview.md
Provides an example of `useLiveInfiniteQuery` for fetching paginated data with live updates. It includes configuration for `pageSize` and `getNextPageParam`, and uses a dependency array to re-fetch when the `category` changes.
```tsx
const { data, pages, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
(q) => q
.from({ posts: postsCollection })
.where(({ posts }) => eq(posts.category, category))
.orderBy(({ posts }) => posts.createdAt, 'desc'),
{
pageSize: 20,
getNextPageParam: (lastPage, allPages) =>
lastPage.length === 20 ? allPages.length : undefined
},
[category] // Re-run when category changes
)
```
--------------------------------
### TanStack DB: Load, Query, and Mutate Data with React
Source: https://github.com/tanstack/db/blob/main/docs/quick-start.md
This example showcases the core functionalities of TanStack DB within a React component. It demonstrates creating a collection that fetches data using TanStack Query, performing live queries to display and filter todos, and implementing optimistic mutations for updating, adding, and deleting todo items.
```tsx
import { createCollection, eq, useLiveQuery } from '@tanstack/react-db'
import { queryCollectionOptions } from '@tanstack/query-db-collection'
// Define a collection that loads data using TanStack Query
const todoCollection = createCollection(
queryCollectionOptions({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetch('/api/todos')
return response.json()
},
getKey: (item) => item.id,
onUpdate: async ({ transaction }) => {
const { original, modified } = transaction.mutations[0]
await fetch(`/api/todos/${original.id}`, {
method: 'PUT',
body: JSON.stringify(modified),
})
},
})
)
function Todos() {
// Live query that updates automatically when data changes
const { data: todos } = useLiveQuery((q) =>
q.from({ todo: todoCollection })
.where(({ todo }) => eq(todo.completed, false))
.orderBy(({ todo }) => todo.createdAt, 'desc')
)
const toggleTodo = (todo) => {
// Instantly applies optimistic state, then syncs to server
todoCollection.update(todo.id, (draft) => {
draft.completed = !draft.completed
})
}
return (
{todos.map((todo) => (
- toggleTodo(todo)}>
{todo.text}
))}
)
}
```
--------------------------------
### Install @tanstack/query-db-collection
Source: https://github.com/tanstack/db/blob/main/docs/collections/query-collection.md
Install the necessary packages for using query collections with TanStack DB and TanStack Query.
```bash
npm install @tanstack/query-db-collection @tanstack/query-core @tanstack/db
```
--------------------------------
### Install Capacitor SQLite Persistence
Source: https://github.com/tanstack/db/blob/main/packages/capacitor-db-sqlite-persistence/README.md
Install the required packages for SQLite persistence in a Capacitor project.
```bash
pnpm add @tanstack/capacitor-db-sqlite-persistence @capacitor-community/sqlite
```
--------------------------------
### SQL Join Optionality Examples
Source: https://github.com/tanstack/db/blob/main/docs/reference/type-aliases/ApplyJoinOptionalityToMergedSchema.md
Illustrative SQL examples showing how different join types affect the optionality of joined tables.
```sql
FROM users LEFT JOIN orders -- orders becomes optional
FROM users RIGHT JOIN orders -- users becomes optional
FROM users FULL JOIN orders -- both become optional
FROM users INNER JOIN orders -- both remain required
```
--------------------------------
### Example deserializationSchema implementation
Source: https://github.com/tanstack/db/blob/main/docs/reference/powersync-db-collection/type-aliases/ConfigWithArbitraryCollectionTypes.md
An example showing how to use Zod to preprocess and validate incoming SQLite data.
```typescript
deserializationSchema: z.object({
createdAt: z.preprocess((val) => new Date(val as string), z.date()),
meta: z.preprocess((val) => JSON.parse(val as string), z.object({ ... })),
})
```
--------------------------------
### startSync Option
Source: https://github.com/tanstack/db/blob/main/docs/reference/interfaces/BaseCollectionConfig.md
Determines whether to eagerly start syncing on collection creation.
```APIDOC
## startSync Option
### Description
Determines whether to eagerly start syncing on collection creation. When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches. Collections pause syncing when there are no active subscribers, resuming when new subscribers attach.
### Type
`boolean`
### Default
`false`
```
--------------------------------
### useLiveQuery with Multiple Dependencies Example
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/overview.md
Illustrates the best practice of including all external values used within the query in the dependency array. This example ensures the query is re-executed when either `userId` or `status` changes, maintaining data consistency.
```tsx
// Good - all external values in deps
const { data } = useLiveQuery(
(q) => q.from({ todos: todosCollection })
.where(({ todos }) => and(
eq(todos.userId, userId),
eq(todos.status, status)
)),
[userId, status]
)
// Bad - missing dependencies
const { data } = useLiveQuery(
(q) => q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.userId, userId)),
[] // Missing userId!
)
```
--------------------------------
### Install TanStack DB Solid Adapter
Source: https://github.com/tanstack/db/blob/main/docs/framework/solid/overview.md
Command to install the TanStack DB Solid adapter package via npm.
```shell
npm install @tanstack/solid-db
```
--------------------------------
### takeFromStart()
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/BasicIndex.md
Returns the first n items in sorted order (from the start). Overrides BaseIndex.takeFromStart.
```APIDOC
## takeFromStart()
### Description
Returns the first n items in sorted order (from the start).
### Method
(Not specified, likely a method call on an index object)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### n
- **n** (number) - Required - The number of items to take from the start.
#### filterFn?
- **filterFn** ((key) => boolean) - Optional - A function to filter the keys.
### Request Example
```typescript
const firstThree = index.takeFromStart(3);
```
### Response
#### Success Response (TKey[])
- **TKey[]** - An array of keys from the start.
#### Response Example
```json
["key1", "key2", "key3"]
```
```
--------------------------------
### Install TanStack Query DB Collection
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/query-adapter.md
Install the necessary packages for TanStack Query DB Collection using pnpm.
```bash
pnpm add @tanstack/query-db-collection @tanstack/query-core @tanstack/db
```
--------------------------------
### takeFromStart()
Source: https://github.com/tanstack/db/blob/main/docs/reference/interfaces/IndexInterface.md
Retrieves a specified number of keys from the start of the index, with an optional filter function.
```APIDOC
## takeFromStart()
### Description
Retrieves a specified number of keys from the start of the index, with an optional filter function.
### Method
N/A (Function Signature)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ts
takeFromStart: (n, filterFn?)
```
### Response
#### Success Response (200)
- **keys** (TKey[]) - An array of keys.
#### Response Example
```ts
// Example return value
["key1", "key2", "key3"]
```
```
--------------------------------
### Install Electric Adapter Dependencies
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/electric-adapter.md
Install the required packages for TanStack Electric DB collection and React integration.
```bash
pnpm add @tanstack/electric-db-collection @tanstack/react-db
```
--------------------------------
### Use Live Query Collections
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/reference/functions/useLiveQuery.md
Examples demonstrating how to use pre-created collections, access collection methods for mutations, and handle loading/error states.
```ts
// Using pre-created live query collection
const myLiveQuery = createLiveQueryCollection((q) =>
q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
)
const { data, collection } = useLiveQuery(myLiveQuery)
```
```ts
// Access collection methods directly
const { data, collection, isReady } = useLiveQuery(existingCollection)
// Use collection for mutations
const handleToggle = (id) => {
collection.update(id, draft => { draft.completed = !draft.completed })
}
```
```ts
// Handle states consistently
const { data, isLoading, isError } = useLiveQuery(sharedCollection)
if (isLoading) return Loading...
if (isError) return Error loading data
return {data.map(item => )}
```
--------------------------------
### Define startSync property
Source: https://github.com/tanstack/db/blob/main/docs/reference/interfaces/LiveQueryCollectionConfig.md
Start sync or the query immediately.
```ts
optional startSync: boolean;
```
--------------------------------
### Example: Create a PowerSync Collection with Zod Validation
Source: https://github.com/tanstack/db/blob/main/docs/reference/powersync-db-collection/functions/powerSyncCollectionOptions.md
This example demonstrates creating a PowerSync collection using `powerSyncCollectionOptions`. It defines the SQLite schema, advanced Zod validations for input/output, and a `deserializationSchema` to convert SQLite integer booleans to JavaScript booleans.
```typescript
import { z } from "zod"
// The PowerSync SQLite schema
const APP_SCHEMA = new Schema({
documents: new Table({
name: column.text,
// Booleans are represented as integers in SQLite
is_active: column.integer
}),
})
// Advanced Zod validations.
// We accept boolean values as input for operations and expose Booleans in query results
const schema = z.object({
id: z.string(),
isActive: z.boolean(), // TInput and TOutput are boolean
})
// The deserializationSchema converts the SQLite synced INTEGER (0/1) values to booleans.
const deserializationSchema = z.object({
id: z.string(),
isActive: z.number().nullable().transform((val) => val == null ? true : val > 0),
})
const collection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents,
schema,
deserializationSchema,
})
)
```
--------------------------------
### Install Tauri SQL plugin
Source: https://github.com/tanstack/db/blob/main/packages/tauri-db-sqlite-persistence/README.md
Add the Tauri SQL plugin to your Tauri project.
```bash
cd src-tauri
cargo add tauri-plugin-sql --features sqlite
```
--------------------------------
### Complete TrailBase Collection Example with Schema and Handlers
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/trailbase-adapter.md
A comprehensive example demonstrating the setup of a TrailBase collection with Zod schema validation, data parsing/serialization for timestamps, and an `onInsert` handler. It also includes an example of how to insert a new record into the collection.
```typescript
import { createCollection } from '@tanstack/react-db'
import { trailBaseCollectionOptions } from '@tanstack/trailbase-db-collection'
import { initClient } from 'trailbase'
import { z } from 'zod'
const trailBaseClient = initClient('https://your-trailbase-instance.com')
const todoSchema = z.object({
id: z.string(),
text: z.string(),
completed: z.boolean(),
created_at: z.date(),
})
type SelectTodo = {
id: string
text: string
completed: boolean
created_at: number
}
type Todo = z.infer
const todosCollection = createCollection(
trailBaseCollectionOptions({
id: 'todos',
recordApi: trailBaseClient.records('todos'),
getKey: (item) => item.id,
schema: todoSchema,
parse: {
created_at: (ts) => new Date(ts * 1000),
},
serialize: {
created_at: (date) => Math.floor(date.valueOf() / 1000),
},
onInsert: async ({ transaction }) => {
console.log('Created:', transaction.mutations[0].modified)
},
}),
)
// Usage
todosCollection.insert({
id: crypto.randomUUID(),
text: 'Review PR',
completed: false,
created_at: new Date(),
})
```
--------------------------------
### Build Project
Source: https://github.com/tanstack/db/blob/main/examples/react/todo/README.md
Run this command to build the project.
```bash
pnpm build
```
--------------------------------
### Configure startSync property
Source: https://github.com/tanstack/db/blob/main/docs/reference/interfaces/BaseCollectionConfig.md
Determines if syncing starts immediately upon collection creation.
```ts
optional startSync: boolean;
```
```ts
false
```
--------------------------------
### Define onLoad Hook
Source: https://github.com/tanstack/db/blob/main/docs/reference/powersync-db-collection/type-aliases/EagerSyncHooks.md
Optional hook called when collection sync starts, allowing for external data source setup.
```ts
optional onLoad: () => CleanupFn | void | Promise;
```
--------------------------------
### Install TanStack DB React Adapter
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/overview.md
Installs the TanStack DB React Adapter using npm. This is the first step to using the adapter in a React project.
```sh
npm install @tanstack/react-db
```
--------------------------------
### Complete Example: Setting Up PowerSync Database and Collections
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/powersync-adapter.md
Defines the application schema, initializes a `PowerSyncDatabase`, and creates a `tasksCollection` with custom options including schema validation and sync batch size. Handles deserialization errors by logging them.
```typescript
import { Schema, Table, column, PowerSyncDatabase } from '@powersync/web'
import { createCollection } from '@tanstack/react-db'
import { powerSyncCollectionOptions } from '@tanstack/powersync-db-collection'
import { z } from 'zod'
const APP_SCHEMA = new Schema({
tasks: new Table({
title: column.text,
due_date: column.text,
completed: column.integer,
}),
})
const db = new PowerSyncDatabase({
database: { dbFilename: 'app.sqlite' },
schema: APP_SCHEMA,
})
const taskSchema = z.object({
id: z.string(),
title: z.string().nullable(),
due_date: z
.string()
.nullable()
.transform((val) => (val ? new Date(val) : null)),
completed:
z
.number()
.nullable()
.transform((val) => (val != null ? val > 0 : null)),
})
const tasksCollection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.tasks,
schema: taskSchema,
onDeserializationError: (error) => console.error('Fatal:', error),
syncBatchSize: 500,
}),
)
```
--------------------------------
### Complete TanStack DB and RxDB Integration Example
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/rxdb-adapter.md
A full example demonstrating the integration of TanStack DB with RxDB. It includes database and collection setup, schema definition using Zod, collection creation with options, and basic data manipulation operations.
```typescript
import { createRxDatabase } from 'rxdb/plugins/core'
import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'
import { createCollection } from '@tanstack/react-db'
import { rxdbCollectionOptions } from '@tanstack/rxdb-db-collection'
import { z } from 'zod'
type Todo = { id: string; text: string; completed: boolean }
const db = await createRxDatabase({
name: 'my-todos',
storage: getRxStorageLocalstorage(),
})
await db.addCollections({
todos: {
schema: {
title: 'todos',
version: 0,
type: 'object',
primaryKey: 'id',
properties: {
id: { type: 'string', maxLength: 100 },
text: { type: 'string' },
completed: { type: 'boolean' },
},
required: ['id', 'text', 'completed'],
},
},
})
const todoSchema = z.object({
id: z.string(),
text: z.string().min(1),
completed: z.boolean(),
})
const todosCollection = createCollection(
rxdbCollectionOptions({
rxCollection: db.todos,
schema: todoSchema,
startSync: true,
syncBatchSize: 500,
}),
)
// Usage
todosCollection.insert({
id: crypto.randomUUID(),
text: 'Buy milk',
completed: false,
})
todosCollection.update('some-id', (draft) => {
draft.completed = true
})
todosCollection.delete('some-id')
```
--------------------------------
### Quick Start: Setting up a Collection with Node SQLite Persistence
Source: https://github.com/tanstack/db/blob/main/packages/node-db-sqlite-persistence/README.md
Demonstrates how to initialize a new collection using Node SQLite persistence. Ensure you manage the database lifecycle and close the connection when your application shuts down.
```typescript
import { createCollection } from '@tanstack/db'
import {
createNodeSQLitePersistence,
persistedCollectionOptions,
} from '@tanstack/node-db-sqlite-persistence'
import Database from 'better-sqlite3'
type Todo = {
id: string
title: string
completed: boolean
}
// You own database lifecycle directly.
const database = new Database(`./tanstack-db.sqlite`)
// One shared persistence instance for the whole database.
const persistence = createNodeSQLitePersistence({
database,
})
export const todosCollection = createCollection(
persistedCollectionOptions({
id: `todos`,
getKey: (todo) => todo.id,
persistence,
schemaVersion: 1, // Per-collection schema version
}),
)
```
--------------------------------
### Electron Collection Coordinator Setup (Main & Renderer)
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/persistence/SKILL.md
Set up Electron persistence by exposing it in the main process and creating it in the renderer process. The renderer process requires an ElectronCollectionCoordinator.
```typescript
// Main process
import { exposeElectronSQLitePersistence } from '@tanstack/electron-db-sqlite-persistence'
exposeElectronSQLitePersistence({ persistence, ipcMain })
// Renderer process
import {
createElectronSQLitePersistence,
ElectronCollectionCoordinator,
} from '@tanstack/electron-db-sqlite-persistence'
const coordinator = new ElectronCollectionCoordinator({ dbName: 'my-app' })
const persistence = createElectronSQLitePersistence({
ipcRenderer: window.electron.ipcRenderer,
coordinator,
})
```
--------------------------------
### Configure Electric Proxy Server
Source: https://github.com/tanstack/db/blob/main/docs/collections/electric-collection.md
An example implementation of an Electric proxy using TanStack Start. It handles request passthrough, parameter filtering, and security headers to safely expose Electric shapes to the client.
```typescript
import { createServerFileRoute } from "@tanstack/react-start/server"
import { ELECTRIC_PROTOCOL_QUERY_PARAMS } from "@electric-sql/client"
const baseUrl = 'http://.../v1/shape'
const serve = async ({ request }: { request: Request }) => {
const url = new URL(request.url)
const originUrl = new URL(baseUrl)
url.searchParams.forEach((value, key) => {
if (ELECTRIC_PROTOCOL_QUERY_PARAMS.includes(key)) {
originUrl.searchParams.set(key, value)
}
})
originUrl.searchParams.set("table", "todos")
const response = await fetch(originUrl)
const headers = new Headers(response.headers)
headers.delete("content-encoding")
headers.delete("content-length")
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
})
}
export const ServerRoute = createServerFileRoute("/api/todos").methods({
GET: serve,
})
```
--------------------------------
### Install TanStack DB for Vue
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the TanStack DB package compatible with Vue.js v3.3.0 or higher.
```sh
npm install @tanstack/vue-db
```
--------------------------------
### Getting Subscriber Count
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/CollectionImpl.md
Get the number of subscribers to the collection.
```ts
get subscriberCount(): number;
```
--------------------------------
### Configure Live Queries with useLiveQuery
Source: https://github.com/tanstack/db/blob/main/docs/framework/vue/reference/functions/useLiveQuery.md
Demonstrates how to initialize live queries using configuration objects or query functions. Includes examples for handling reactive dependencies and managing UI states like loading and errors.
```typescript
// Basic config object usage
const { data, status } = useLiveQuery({
query: (q) => q.from({ todos: todosCollection }),
gcTime: 60000
});
// With reactive dependencies
const filter = ref('active');
const { data, isReady } = useLiveQuery({
query: (q) => q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.status, filter.value))
}, [filter]);
```
--------------------------------
### Create a Basic Query Collection
Source: https://github.com/tanstack/db/blob/main/docs/collections/query-collection.md
Demonstrates the basic setup for creating a query collection, including defining query options and fetching data.
```typescript
import { QueryClient } from "@tanstack/query-core"
import { createCollection } from "@tanstack/db"
import { queryCollectionOptions } from "@tanstack/query-db-collection"
const queryClient = new QueryClient()
const todosCollection = createCollection(
queryCollectionOptions({
queryKey: ["todos"],
queryFn: async () => {
const response = await fetch("/api/todos")
return response.json()
},
queryClient,
getKey: (item) => item.id,
})
)
```
--------------------------------
### Install TanStack DB TrailBase Collection
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the collection package for syncing data with TrailBase backends, including built-in subscription support for records.
```sh
npm install @tanstack/trailbase-db-collection
```
--------------------------------
### useLiveQuery with Pre-created Collection
Source: https://github.com/tanstack/db/blob/main/packages/solid-db/skills/solid-db/SKILL.md
Shows how to initialize useLiveQuery with a pre-created collection object. The collection should be passed as an Accessor.
```javascript
// Pre-created collection — pass as Accessor
const query = useLiveQuery(() => preloadedCollection)
```
--------------------------------
### Basic useLiveQuery Configuration
Source: https://github.com/tanstack/db/blob/main/docs/framework/solid/reference/functions/useLiveQuery.md
Demonstrates the basic configuration object usage for useLiveQuery with a garbage collection time.
```typescript
// Basic config object usage
const todosQuery = useLiveQuery(() => ({
query: (q) => q.from({ todos: todosCollection }),
gcTime: 60000
}))
```
--------------------------------
### Install TanStack DB Electric Collection
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the collection package for real-time data synchronization with ElectricSQL. Enables syncing data from Postgres databases.
```sh
npm install @tanstack/electric-db-collection
```
--------------------------------
### Create New TanStack DB Project
Source: https://github.com/tanstack/db/blob/main/examples/react/projects/README.md
Commands to initialize a new project using the TanStack DB starter template. This involves cloning the example project and navigating into the new project directory.
```bash
npx gitpick tanstack/db/tree/main/examples/react/projects my-tanstack-db-project
cd my-tanstack-db-project
```
--------------------------------
### Install TanStack DB Query Collection
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the collection package for integrating TanStack DB with TanStack Query, useful for fetching data from REST APIs.
```sh
npm install @tanstack/query-db-collection
```
--------------------------------
### Setup useLiveQuery in Svelte 5
Source: https://github.com/tanstack/db/blob/main/packages/svelte-db/skills/svelte-db/SKILL.md
Demonstrates how to set up and use the `useLiveQuery` hook in a Svelte 5 component to fetch and display a list of incomplete todos.
```svelte
{#if todosQuery.isLoading}
Loading...
{:else}
{#each todosQuery.data as todo (todo.id)}
- {todo.text}
{/each}
{/if}
```
--------------------------------
### Install Core TanStack DB for Vanilla JS
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the core TanStack DB package for use in vanilla JavaScript projects without a specific framework.
```sh
npm install @tanstack/db
```
--------------------------------
### Functional Having Callback Examples
Source: https://github.com/tanstack/db/blob/main/docs/reference/type-aliases/FunctionalHavingRow.md
Usage examples for functional having callbacks with and without GROUP BY.
```ts
({ $selected }) => $selected.sessionCount > 2
```
```ts
(row) => row.user.salary > 70000 && row.$selected.user_count > 2
```
--------------------------------
### PowerSync Collection Creation Example
Source: https://github.com/tanstack/db/blob/main/docs/reference/powersync-db-collection/type-aliases/PowerSyncCollectionConfig.md
Demonstrates how to create a PowerSync collection using a defined schema and database instance. Ensure PowerSyncDatabase and Schema are properly initialized.
```typescript
const APP_SCHEMA = new Schema({
documents: new Table({
name: column.text,
}),
})
const db = new PowerSyncDatabase({
database: {
dbFilename: "test.sqlite",
},
schema: APP_SCHEMA,
})
const collection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents
})
)
```
--------------------------------
### Install TanStack DB RxDB Collection
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the collection package for integrating TanStack DB with RxDB, providing offline-first capabilities with local persistence, replication, and conflict handling.
```sh
npm install @tanstack/rxdb-db-collection
```
--------------------------------
### Example of basic collection configuration
Source: https://github.com/tanstack/db/blob/main/docs/reference/powersync-db-collection/functions/powerSyncCollectionOptions.md
Demonstrates creating a collection configuration without schema validation.
```typescript
const APP_SCHEMA = new Schema({
documents: new Table({
name: column.text,
}),
})
type Document = (typeof APP_SCHEMA)["types"]["documents"]
const db = new PowerSyncDatabase({
database: {
dbFilename: "test.sqlite",
},
schema: APP_SCHEMA,
})
const collection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents
})
)
```
--------------------------------
### Install TanStack DB PowerSync Collection (Web)
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the PowerSync collection package along with necessary web-specific PowerSync SDK and SQLite adapter for offline-first sync on the web.
```sh
npm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite
```
--------------------------------
### Basic PowerSync Configuration
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/collection-setup/references/powersync-adapter.md
Set up a PowerSyncDatabase instance and create a collection with a defined schema.
```typescript
import { createCollection } from '@tanstack/react-db'
import { powerSyncCollectionOptions } from '@tanstack/powersync-db-collection'
import { Schema, Table, column, PowerSyncDatabase } from '@powersync/web'
const APP_SCHEMA = new Schema({
documents: new Table({
name: column.text,
author: column.text,
created_at: column.text,
archived: column.integer,
}),
})
const db = new PowerSyncDatabase({
database: { dbFilename: 'app.sqlite' },
schema: APP_SCHEMA,
})
const documentsCollection = createCollection(
powerSyncCollectionOptions({
database: db,
table: APP_SCHEMA.props.documents,
}),
)
```
--------------------------------
### Basic useLiveQuery with Object Syntax
Source: https://github.com/tanstack/db/blob/main/docs/framework/solid/reference/functions/useLiveQuery.md
A basic example of creating a live query using the object syntax for the query function.
```typescript
// Basic query with object syntax
const todosQuery = useLiveQuery((q) =>
q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.completed, false))
.select(({ todos }) => ({ id: todos.id, text: todos.text }))
)
```
--------------------------------
### Example Usage of GroupByCallback
Source: https://github.com/tanstack/db/blob/main/docs/reference/type-aliases/GroupByCallback.md
A simple example showing how to access a table status field within the callback.
```ts
(refs) => refs.orders.status
```
--------------------------------
### Setup useLiveQuery in a React Component
Source: https://github.com/tanstack/db/blob/main/packages/react-db/skills/react-db/SKILL.md
Demonstrates how to set up and use the `useLiveQuery` hook to fetch and display a list of incomplete todos. Imports necessary functions and assumes `todoCollection` is defined elsewhere.
```tsx
import { useLiveQuery, eq, not } from '@tanstack/react-db'
function TodoList() {
const { data: todos, isLoading } = useLiveQuery((q) =>
q
.from({ todo: todoCollection })
.where(({ todo }) => not(todo.completed))
.orderBy(({ todo }) => todo.created_at, 'asc'),
)
if (isLoading) return Loading...
return (
{todos.map((todo) => (
- {todo.text}
))}
)
}
```
--------------------------------
### Create Live Query Collection with Full Options
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/db-core/live-queries/SKILL.md
Illustrates creating a live query collection using the full options object, specifying the query and a key getter function.
```typescript
// Option 2: full options via liveQueryCollectionOptions
const activeUsers2 = createCollection(
liveQueryCollectionOptions({
query: (q) =>
q
.from({ user: usersCollection })
.where(({ user }) => eq(user.active, true))
.select(({ user }) => ({
id: user.id,
name: user.name,
})),
getKey: (user) => user.id,
}),
)
```
--------------------------------
### Install TanStack DB PowerSync Collection (React Native)
Source: https://github.com/tanstack/db/blob/main/docs/installation.md
Installs the PowerSync collection package along with necessary React Native-specific PowerSync SDK and SQLite adapter for offline-first sync on React Native.
```sh
npm install @tanstack/powersync-db-collection @powersync/react-native @powersync/op-sqlite @op-engineering/op-sqlite
```
--------------------------------
### useLiveQuery with Configuration Object
Source: https://github.com/tanstack/db/blob/main/packages/solid-db/skills/solid-db/SKILL.md
Demonstrates passing a configuration object to useLiveQuery, including the query definition and garbage collection time. The configuration itself can be reactive.
```javascript
// Config object — pass as Accessor
const query = useLiveQuery(() => ({ query: (q) => q.from({ todo: todoCollection }), gcTime: 60000 }))
```
--------------------------------
### Disable Global SSR in TanStack Start
Source: https://github.com/tanstack/db/blob/main/packages/db/skills/meta-framework/SKILL.md
Configure TanStack Start to disable Server-Side Rendering globally for all routes.
```typescript
// start.tsx
import { createStart } from '@tanstack/react-start'
export const startInstance = createStart(() => {
return {
defaultSsr: false,
}
})
```
--------------------------------
### useLiveQuery with Configuration Object
Source: https://github.com/tanstack/db/blob/main/docs/framework/svelte/reference/functions/useLiveQuery.md
This snippet demonstrates the basic usage of useLiveQuery with a configuration object, including query definition and optional garbage collection time.
```APIDOC
## POST /api/users
### Description
Creates a new user in the system.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Request Body
- **name** (string) - Required - The name of the user.
- **email** (string) - Required - The email address of the user.
### Request Example
```json
{
"name": "John Doe",
"email": "john.doe@example.com"
}
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier of the newly created user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
#### Response Example
```json
{
"id": "user-123",
"name": "John Doe",
"email": "john.doe@example.com"
}
```
```
--------------------------------
### Install @tanstack/offline-transactions
Source: https://github.com/tanstack/db/blob/main/packages/offline-transactions/README.md
Installation commands for the offline-transactions package, including platform-specific peer dependencies for React Native.
```bash
npm install @tanstack/offline-transactions
```
```bash
npm install @tanstack/offline-transactions @react-native-community/netinfo
```
--------------------------------
### startSync Configuration
Source: https://github.com/tanstack/db/blob/main/docs/reference/interfaces/CollectionConfig.md
Controls whether syncing starts immediately on collection creation or when the first subscriber attaches.
```APIDOC
## startSync
### Description
Whether to eagerly start syncing on collection creation. When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches. Note: Even with startSync=true, collections will pause syncing when there are no active subscribers (typically when components querying the collection unmount), resuming when new subscribers attach. This preserves normal staleTime/gcTime behavior.
### Method
Not Applicable (Configuration Option)
### Endpoint
Not Applicable (Configuration Option)
### Parameters
#### Query Parameters
- **startSync** (boolean) - Optional - Controls eager syncing behavior.
### Request Example
```json
{
"startSync": true
}
```
### Response
#### Success Response (200)
Not Applicable (Configuration Option)
#### Response Example
```json
{
"startSync": false
}
```
#### Default
`false`
```
--------------------------------
### Install TanStack DB Svelte Adapter
Source: https://github.com/tanstack/db/blob/main/docs/framework/svelte/overview.md
Command to install the necessary package for Svelte integration.
```shell
npm install @tanstack/svelte-db
```
--------------------------------
### Install RxDB Collection Dependencies
Source: https://github.com/tanstack/db/blob/main/docs/collections/rxdb-collection.md
Installs the required packages for integrating TanStack DB with RxDB.
```bash
npm install @tanstack/rxdb-db-collection rxdb @tanstack/react-db
```
--------------------------------
### Ref Usage Examples
Source: https://github.com/tanstack/db/blob/main/docs/reference/type-aliases/Ref.md
Demonstrates how to use Ref for clean property access, handling nullable joins, and spreading results.
```typescript
// Clean interface - no internal properties visible
const users: Ref<{ id: number; profile?: { bio: string } }> = { ... }
users.id // Ref - clean display
users.profile?.bio // Ref - nested optional access works
users.$synced // RefLeaf - virtual property access
// Nullable ref (left/right/full join side):
select(({ dept }) => ({ name: dept.name })) // result: string | undefined
// Spread operations work cleanly:
select(({ user }) => ({ ...user })) // Returns User type, not Ref types
```
--------------------------------
### Diagnose Duplicate @tanstack/db Installations
Source: https://github.com/tanstack/db/blob/main/packages/react-db/skills/react-db/SKILL.md
Run this command to check for multiple versions of @tanstack/db installed in your project. This helps diagnose the 'Not a Collection' error.
```bash
pnpm ls @tanstack/db
```
--------------------------------
### Install @tanstack/angular-db and @tanstack/db
Source: https://github.com/tanstack/db/blob/main/packages/angular-db/README.md
Installs the necessary packages for using TanStack DB with Angular. This is the first step before utilizing any of the library's features.
```bash
npm install @tanstack/angular-db @tanstack/db
```
--------------------------------
### Get Item by Key
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/CollectionImpl.md
Use the `get()` method to retrieve the current value for a specific key from the collection. This method accounts for virtual derived state.
```typescript
get(key):
| WithVirtualProps
| undefined;
```
--------------------------------
### useLiveQuery with Reactive Dependencies
Source: https://github.com/tanstack/db/blob/main/docs/framework/svelte/reference/functions/useLiveQuery.md
This example shows how to use reactive dependencies with useLiveQuery. The query will automatically re-execute when the specified dependencies change.
```APIDOC
## GET /api/users/{userId}
### Description
Retrieves a specific user by their ID.
### Method
GET
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to retrieve.
### Response
#### Success Response (200)
- **id** (string) - The unique identifier of the user.
- **name** (string) - The name of the user.
- **email** (string) - The email address of the user.
#### Response Example
```json
{
"id": "user-123",
"name": "John Doe",
"email": "john.doe@example.com"
}
```
```
--------------------------------
### Basic useLiveQuery with Object Syntax
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/reference/functions/useLiveQuery.md
Demonstrates a basic live query using object syntax to fetch incomplete todos. Requires the 'todosCollection' to be defined.
```typescript
const { data, isLoading } = useLiveQuery((q) =>
q.from({ todos: todosCollection })
.where(({ todos }) => eq(todos.completed, false))
.select(({ todos }) => ({ id: todos.id, text: todos.text }))
)
```
--------------------------------
### takeFromStart()
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/BTreeIndex.md
Returns the first n items from the beginning. Overrides BaseIndex.takeFromStart.
```APIDOC
## takeFromStart()
### Description
Returns the first n items from the beginning.
### Method
(Not specified, likely a method call)
### Endpoint
(Not applicable, this is a method)
### Parameters
#### Path Parameters
(None)
#### Query Parameters
(None)
#### Request Body
(None)
### Request Example
(Not applicable)
### Response
#### Success Response (200)
- **n** (number) - The number of items to return.
- **filterFn?** (function) - Optional filter function `(key) => boolean`.
- **TKey[]** - The first n items.
#### Response Example
(Not applicable)
```
--------------------------------
### Install TanStack DB Angular Adapter
Source: https://github.com/tanstack/db/blob/main/docs/framework/angular/overview.md
Command to install the TanStack DB Angular adapter package via npm.
```shell
npm install @tanstack/angular-db
```
--------------------------------
### useLiveQuery with Configuration Object
Source: https://github.com/tanstack/db/blob/main/packages/vue-db/skills/vue-db/SKILL.md
Demonstrates using useLiveQuery with a configuration object, allowing for options like gcTime. Requires a pre-defined todoCollection.
```typescript
// Config object
const { data } = useLiveQuery({
query: (q) => q.from({ todo: todoCollection }),
gcTime: 60000,
})
```
--------------------------------
### Query with Dependencies for Re-execution
Source: https://github.com/tanstack/db/blob/main/docs/framework/react/reference/functions/useLiveQuery.md
This example shows how to re-execute a query when specific dependencies change. Pass an array of dependencies as the second argument to useLiveQuery.
```typescript
// With dependencies that trigger re-execution
const { data, state } = useLiveQuery(
(q) => q.from({ todos: todosCollection })
.where(({ todos }) => gt(todos.priority, minPriority)),
[minPriority] // Re-run when minPriority changes
)
```
--------------------------------
### Start Immediate Collection Synchronization
Source: https://github.com/tanstack/db/blob/main/docs/reference/classes/CollectionImpl.md
Forces the collection synchronization process to start immediately. This is an internal method primarily used for compiled queries to bypass lazy loading.
```typescript
startSyncImmediate(): void;
```
--------------------------------
### Install TrailBase Collection Dependencies
Source: https://github.com/tanstack/db/blob/main/docs/collections/trailbase-collection.md
Installs the necessary packages for integrating TanStack DB with TrailBase, including the collection package, React DB, and TrailBase itself.
```bash
npm install @tanstack/trailbase-db-collection @tanstack/react-db trailbase
```