Defined in: packages/db/src/collection/index.ts:145
Enhanced Collection interface that includes both data type T and utilities TUtils
T extends object = Record<string, unknown>
The type of items in the collection
TKey extends string | number = string | number
The type of the key for the collection
TUtils extends UtilsRecord = UtilsRecord
The utilities record type
TSchema extends StandardSchemaV1 = StandardSchemaV1
TInsertInput extends object = T
The type for insert operations (can be different from T for schemas with defaults)
_lifecycle: CollectionLifecycleManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:384
_state: CollectionStateManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:396
_sync: CollectionSyncManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:385
config: CollectionConfig<T, TKey, TSchema, TUtils>;Defined in: packages/db/src/collection/index.ts:375
deferDataRefresh: Promise<void> | null = null;Defined in: packages/db/src/collection/index.ts:403
When set, collection consumers should defer processing incoming data refreshes until this promise resolves. This prevents stale data from overwriting optimistic state while pending writes are being applied.
CollectionImpl.deferDataRefresh
id: string;Defined in: packages/db/src/collection/index.ts:374
readonly optional singleResult: true;Defined in: packages/db/src/collection/index.ts:153
readonly utils: TUtils;Defined in: packages/db/src/collection/index.ts:152
get _layoutRevision(): number;Defined in: packages/db/src/collection/index.ts:548
Monotonic revision of explicit layout-only publications. Internal — used to distinguish them from empty ready events.
number
CollectionImpl._layoutRevision
get _stateRevision(): number;Defined in: packages/db/src/collection/index.ts:540
Monotonic revision of the collection's visible state; advances once per committed batch of changes and cleanup, even while nothing is subscribed. Internal — used by the live-query observer's snapshot cache.
number
get base(): CollectionBase<TKey, TOutput>;Defined in: packages/db/src/collection/index.ts:657
The exposed authoritative base rows, before optimistic writes are applied. Queued sync writes are excluded. Reading does not start sync. Do not mutate the backing map or its rows: that bypasses publication.
CollectionBase<TKey, TOutput>
get compareOptions(): StringCollationConfig;Defined in: packages/db/src/collection/index.ts:828
get indexes(): Map<number, BaseIndex<TKey>>;Defined in: packages/db/src/collection/index.ts:813
Get resolved indexes for query optimization
Map<number, BaseIndex<TKey>>
get isLoadingSubset(): boolean;Defined in: packages/db/src/collection/index.ts:606
Check if the collection is currently loading more data
boolean
true if the collection has pending load more operations, false otherwise
CollectionImpl.isLoadingSubset
get size(): number;Defined in: packages/db/src/collection/index.ts:678
Get the current size of the collection (cached)
number
get state(): Map<TKey, WithVirtualProps<TOutput, TKey>>;Defined in: packages/db/src/collection/index.ts:1005
Gets the current state of the collection as a Map
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)
for (const [key, item] of itemsMap) {
console.log(`${key}: ${item.title}`)
}
// Check if specific item exists
if (itemsMap.has("todo-1")) {
console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}Map<TKey, WithVirtualProps<TOutput, TKey>>
Map containing all items in the collection, with keys as identifiers
get status(): CollectionStatus;Defined in: packages/db/src/collection/index.ts:524
Gets the current status of the collection
get subscriberCount(): number;Defined in: packages/db/src/collection/index.ts:531
Get the number of subscribers to the collection
number
CollectionImpl.subscriberCount
get toArray(): WithVirtualProps<TOutput, TKey>[];Defined in: packages/db/src/collection/index.ts:1034
Gets the current state of the collection as an Array
WithVirtualProps<TOutput, TKey>[]
An Array containing all items in the collection
_deferPublication(): PublicationDeferral;Defined in: packages/db/src/collection/index.ts:563
Defer subscriber events until a coherent multi-Collection commit ends.
PublicationDeferral
CollectionImpl._deferPublication
_deferSyncStart(): boolean;Defined in: packages/db/src/collection/index.ts:635
Internal
boolean
CollectionImpl._deferSyncStart
_hasHydratedKey(key): boolean;Defined in: packages/db/src/collection/index.ts:630
Internal
TKey
boolean
CollectionImpl._hasHydratedKey
_markLayoutChange(): void;Defined in: packages/db/src/collection/index.ts:558
Mark the active sync transaction as layout-changing. Internal.
void
CollectionImpl._markLayoutChange
_onCleanupStart(callback): () => void;Defined in: packages/db/src/collection/index.ts:620
Internal
Subscribe to the synchronous cleanup-start boundary.
() => void
(): void;void
CollectionImpl._onCleanupStart
_resumeSyncStart(): void;Defined in: packages/db/src/collection/index.ts:640
Internal
void
CollectionImpl._resumeSyncStart
_setTransactionScope(transactionScope): void;Defined in: packages/db/src/collection/index.ts:625
Internal
void
CollectionImpl._setTransactionScope
_subscribeLayoutChanges(listener): () => void;Defined in: packages/db/src/collection/index.ts:553
Subscribe to layout-only publications. Internal observer channel.
() => void
(): void;void
CollectionImpl._subscribeLayoutChanges
iterator: IterableIterator<[TKey, WithVirtualProps<T, TKey>]>;Defined in: packages/db/src/collection/index.ts:716
Get all entries (virtual derived state)
IterableIterator<[TKey, WithVirtualProps<T, TKey>]>
cleanup(): Promise<void>;Defined in: packages/db/src/collection/index.ts:1206
Clean up the collection by stopping sync and clearing data This can be called manually or automatically by garbage collection Cleanup callbacks must not restart this collection or call its preload(). Wait until cleanup completes before starting a new sync run. If adapter cleanup rejects, this promise rejects after the Collection reaches its final cleaned-up state.
Promise<void>
createIndex<TIndexType>(indexCallback, config): BaseIndex<TKey>;Defined in: packages/db/src/collection/index.ts:782
Creates an index on a collection for faster queries. Indexes significantly improve query performance by allowing constant time lookups and logarithmic time range queries instead of full scans.
TIndexType extends IndexConstructor<TKey>
(row) => any
Function that extracts the indexed value from each item
IndexOptions<TIndexType> = {}
Configuration including index type and type-specific options
BaseIndex<TKey>
The created index
import { BasicIndex } from '@tanstack/db'
// Create an index with explicit type
const ageIndex = collection.createIndex((row) => row.age, {
indexType: BasicIndex
})
// Create an index with collection's default type
const nameIndex = collection.createIndex((row) => row.name)currentStateAsChanges(options):
| void
| ChangeMessage<WithVirtualProps<T, TKey>, TKey>[];Defined in: packages/db/src/collection/index.ts:1072
Returns the current state of the collection as an array of changes
CurrentStateAsChangesOptions = {}
Options including optional where filter
| void | ChangeMessage<WithVirtualProps<T, TKey>, TKey>[]
An array of changes
// Get all items as changes
const allChanges = collection.currentStateAsChanges()
// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
where: (row) => row.status === 'active'
})
// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
whereExpression: eq(row.status, 'active')
})CollectionImpl.currentStateAsChanges
delete(keys, config?): Transaction<any>;Defined in: packages/db/src/collection/index.ts:982
Deletes one or more items from the collection
Single key or array of keys to delete
TKey | TKey[]
Optional configuration including metadata
Transaction<any>
A Transaction object representing the delete operation(s)
// Delete a single item
const tx = collection.delete("todo-1")
await tx.when('settled')// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.when('settled')// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.when('settled')// Handle errors
try {
const tx = collection.delete("item-1")
await tx.when('settled')
console.log('Delete successful')
} catch (error) {
console.log('Delete failed:', error)
}entries(): IterableIterator<[TKey, WithVirtualProps<T, TKey>]>;Defined in: packages/db/src/collection/index.ts:704
Get all entries (virtual derived state)
IterableIterator<[TKey, WithVirtualProps<T, TKey>]>
forEach(callbackfn): void;Defined in: packages/db/src/collection/index.ts:725
Execute a callback for each entry in the collection
(value, key, index) => void
void
get(key):
| WithVirtualProps<T, TKey>
| undefined;Defined in: packages/db/src/collection/index.ts:664
Get the current value for a key (virtual derived state)
TKey
| WithVirtualProps<T, TKey> | undefined
getIndexMetadata(): CollectionIndexMetadata[];Defined in: packages/db/src/collection/index.ts:806
Returns a snapshot of current index metadata sorted by indexId. Persistence wrappers can use this to bootstrap index state if indexes were created before event listeners were attached.
CollectionImpl.getIndexMetadata
getKeyFromItem(item): TKey;Defined in: packages/db/src/collection/index.ts:756
T
TKey
has(key): boolean;Defined in: packages/db/src/collection/index.ts:671
Check if a key exists in the collection (virtual derived state)
TKey
boolean
insert(data, config?): Transaction<Record<string, unknown>>;Defined in: packages/db/src/collection/index.ts:869
Inserts one or more items into the collection
TInsertInput | TInsertInput[]
Optional configuration including metadata
Transaction<Record<string, unknown>>
A Transaction object representing the insert operation(s)
If the data fails schema validation
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.when('settled')// Insert multiple todos at once
const tx = collection.insert([
{ id: "1", text: "Buy milk", completed: false },
{ id: "2", text: "Walk dog", completed: true }
])
await tx.when('settled')// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
{ metadata: { source: "mobile-app" } }
)
await tx.when('settled')// Handle errors
try {
const tx = collection.insert({ id: "1", text: "New item" })
await tx.when('settled')
console.log('Insert successful')
} catch (error) {
console.log('Insert failed:', error)
}isReady(): boolean;Defined in: packages/db/src/collection/index.ts:598
Check if the collection is ready for use Returns true if the collection has been marked as ready by its sync implementation
boolean
true if the collection is ready, false otherwise
if (collection.isReady()) {
console.log('Collection is ready, data is available')
// Safe to access collection.state
} else {
console.log('Collection is still loading')
}keys(): IterableIterator<TKey>;Defined in: packages/db/src/collection/index.ts:685
Get all keys (virtual derived state)
IterableIterator<TKey>
map<U>(callbackfn): U[];Defined in: packages/db/src/collection/index.ts:741
Create a new array with the results of calling a function for each entry in the collection
U
(value, key, index) => U
U[]
off<T>(event, callback): void;Defined in: packages/db/src/collection/index.ts:1181
Unsubscribe from a collection event
T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"
T
CollectionEventHandler<T>
void
on<T>(event, callback): () => void;Defined in: packages/db/src/collection/index.ts:1161
Subscribe to a collection event
T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"
T
CollectionEventHandler<T>
(): void;void
once<T>(event, callback): () => void;Defined in: packages/db/src/collection/index.ts:1171
Subscribe to a collection event once
T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"
T
CollectionEventHandler<T>
(): void;void
onFirstReady(callback): () => void;Defined in: packages/db/src/collection/index.ts:582
Register a callback to be executed when the collection first becomes ready Useful for preloading collections Every callback queued before the transition runs. Because ready state is established first, callbacks registered during or after delivery run immediately. If one throws, the collection remains ready. Direct sync startup rethrows the first failure; preload resolves from ready state. Cleanup discards pending callbacks without invoking them.
() => void
Function to call when the collection first becomes ready
(): void;void
collection.onFirstReady(() => {
console.log('Collection is ready for the first time')
// Safe to access collection.state now
})preload(): Promise<void>;Defined in: packages/db/src/collection/index.ts:648
Preload the collection data by starting sync if not already started Multiple concurrent calls will share the same promise
Promise<void>
removeIndex(indexOrId): boolean;Defined in: packages/db/src/collection/index.ts:797
Removes an index created with createIndex. Returns true when an index existed and was removed.
Best-effort semantics: removing an index guarantees it is detached from collection query planning. Existing index proxy references should be treated as invalid after removal.
number | BaseIndex<TKey>
boolean
startSyncImmediate(): void;Defined in: packages/db/src/collection/index.ts:615
Start sync immediately - internal method for compiled queries This bypasses lazy loading for special cases like live query results Throws during active cleanup; restart after cleanup completes instead.
void
CollectionImpl.startSyncImmediate
stateWhenReady(): Promise<Map<TKey, WithVirtualProps<T, TKey>>>;Defined in: packages/db/src/collection/index.ts:1019
Gets the current state of the collection as a Map, but only resolves when data is available Waits for the first sync commit to complete before resolving
Promise<Map<TKey, WithVirtualProps<T, TKey>>>
Promise that resolves to a Map containing all items in the collection
subscribeChanges(callback, options?): CollectionSubscription;Defined in: packages/db/src/collection/index.ts:1124
Subscribe to changes in the collection Changes to the same key retain their causal order within a callback. Changes to different keys have no promised order within a callback.
(changes) => void
Function called when items change
SubscribeChangesOptions<T, TKey>
Subscription options including includeInitialState and where filter
CollectionSubscription
Unsubscribe function - Call this to stop listening for changes
// Basic subscription
const subscription = collection.subscribeChanges((changes) => {
changes.forEach(change => {
console.log(`${change.type}: ${change.key}`, change.value)
})
})
// Later: subscription.unsubscribe()// Include current state immediately
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, { includeInitialState: true })// Subscribe only to changes matching a condition using where callback
import { eq } from "@tanstack/db"
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
where: (row) => eq(row.status, "active")
})// Using multiple conditions with and()
import { and, eq, gt } from "@tanstack/db"
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
where: (row) => and(eq(row.status, "active"), gt(row.priority, 5))
})CollectionImpl.subscribeChanges
subscribeChanges(callback, options?): CollectionSubscription;Defined in: packages/db/src/collection/index.ts:1132
Subscribe to changes in the collection Changes to the same key retain their causal order within a callback. Changes to different keys have no promised order within a callback.
Function called when items change
(changes) => void | (changes) => void
SubscribeChangesOptions<T, TKey>
Subscription options including includeInitialState and where filter
CollectionSubscription
Unsubscribe function - Call this to stop listening for changes
// Basic subscription
const subscription = collection.subscribeChanges((changes) => {
changes.forEach(change => {
console.log(`${change.type}: ${change.key}`, change.value)
})
})
// Later: subscription.unsubscribe()// Include current state immediately
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, { includeInitialState: true })// Subscribe only to changes matching a condition using where callback
import { eq } from "@tanstack/db"
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
includeInitialState: true,
where: (row) => eq(row.status, "active")
})// Using multiple conditions with and()
import { and, eq, gt } from "@tanstack/db"
const subscription = collection.subscribeChanges((changes) => {
updateUI(changes)
}, {
where: (row) => and(eq(row.status, "active"), gt(row.priority, 5))
})CollectionImpl.subscribeChanges
toArrayWhenReady(): Promise<WithVirtualProps<T, TKey>[]>;Defined in: packages/db/src/collection/index.ts:1044
Gets the current state of the collection as an Array, but only resolves when data is available Waits for the first sync commit to complete before resolving
Promise<WithVirtualProps<T, TKey>[]>
Promise that resolves to an Array containing all items in the collection
CollectionImpl.toArrayWhenReady
update(key, callback): Transaction;Defined in: packages/db/src/collection/index.ts:914
Updates one or more items in the collection using a callback function
TKey[]
(drafts) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.when('settled')// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.when('settled')// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.when('settled')// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.when('settled')
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}update(
keys,
config,
callback): Transaction;Defined in: packages/db/src/collection/index.ts:920
Updates one or more items in the collection using a callback function
TKey[]
Single key or array of keys to update
(drafts) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.when('settled')// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.when('settled')// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.when('settled')// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.when('settled')
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}update(id, callback): Transaction;Defined in: packages/db/src/collection/index.ts:927
Updates one or more items in the collection using a callback function
TKey
(draft) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.when('settled')// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.when('settled')// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.when('settled')// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.when('settled')
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}update(
id,
config,
callback): Transaction;Defined in: packages/db/src/collection/index.ts:933
Updates one or more items in the collection using a callback function
TKey
(draft) => void
A Transaction object representing the update operation(s)
If the updated data fails schema validation
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
draft.completed = true
})
await tx.when('settled')// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
drafts.forEach(draft => { draft.completed = true })
})
await tx.when('settled')// Update with metadata
const tx = collection.update("todo-1",
{ metadata: { reason: "user update" } },
(draft) => { draft.text = "Updated text" }
)
await tx.when('settled')// Handle errors
try {
const tx = collection.update("item-1", draft => { draft.value = "new" })
await tx.when('settled')
console.log('Update successful')
} catch (error) {
console.log('Update failed:', error)
}validateData(
data,
type,
key?): T;Defined in: packages/db/src/collection/index.ts:820
Validates the data against the schema
unknown
"insert" | "update"
TKey
T
values(): IterableIterator<WithVirtualProps<T, TKey>>;Defined in: packages/db/src/collection/index.ts:692
Get all values (virtual derived state)
IterableIterator<WithVirtualProps<T, TKey>>
waitFor<T>(event, timeout?): Promise<AllCollectionEvents[T]>;Defined in: packages/db/src/collection/index.ts:1191
Wait for a collection event
T extends | "status:error" | "status:idle" | "status:loading" | "status:ready" | "status:cleaned-up" | "status:change" | "subscribers:change" | "loadingSubset:change" | "truncate" | "index:added" | "index:removed"
T
number
Promise<AllCollectionEvents[T]>