Collection
Defined in: packages/db/src/collection/index.ts:148
Enhanced Collection interface that includes both data type T and utilities TUtils
Extends
CollectionImpl<T,TKey,TUtils,TSchema,TInsertInput>
Type Parameters
T
T extends object = Record<string, unknown>
The type of items in the collection
TKey
TKey extends string | number = string | number
The type of the key for the collection
TUtils
TUtils extends UtilsRecord = UtilsRecord
The utilities record type
TSchema
TSchema extends StandardSchemaV1 = StandardSchemaV1
TInsertInput
TInsertInput extends object = T
The type for insert operations (can be different from T for schemas with defaults)
Properties
_lifecycle
_lifecycle: CollectionLifecycleManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:397
Inherited from
_state
_state: CollectionStateManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:409
Inherited from
_sync
_sync: CollectionSyncManager<T, TKey, TSchema, TInsertInput>;Defined in: packages/db/src/collection/index.ts:398
Inherited from
config
config: CollectionConfig<T, TKey, TSchema, TUtils>;Defined in: packages/db/src/collection/index.ts:388
Inherited from
deferDataRefresh
deferDataRefresh: Promise<void> | null = null;Defined in: packages/db/src/collection/index.ts:416
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.
Inherited from
CollectionImpl.deferDataRefresh
id
id: string;Defined in: packages/db/src/collection/index.ts:387
Inherited from
singleResult?
readonly optional singleResult: true;Defined in: packages/db/src/collection/index.ts:156
utils
readonly utils: TUtils;Defined in: packages/db/src/collection/index.ts:155
Overrides
Accessors
_layoutRevision
Get Signature
get _layoutRevision(): number;Defined in: packages/db/src/collection/index.ts:564
Monotonic revision of explicit layout-only publications. Internal — used to distinguish them from empty ready events.
Returns
number
Inherited from
CollectionImpl._layoutRevision
_stateRevision
Get Signature
get _stateRevision(): number;Defined in: packages/db/src/collection/index.ts:556
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.
Returns
number
Inherited from
base
Get Signature
get base(): CollectionBase<TKey, TOutput>;Defined in: packages/db/src/collection/index.ts:704
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.
Returns
CollectionBase<TKey, TOutput>
Inherited from
compareOptions
Get Signature
get compareOptions(): StringCollationConfig;Defined in: packages/db/src/collection/index.ts:884
Returns
Inherited from
indexes
Get Signature
get indexes(): Map<number, BaseIndex<TKey>>;Defined in: packages/db/src/collection/index.ts:869
Get resolved indexes for query optimization
Returns
Map<number, BaseIndex<TKey>>
Inherited from
isLoadingSubset
Get Signature
get isLoadingSubset(): boolean;Defined in: packages/db/src/collection/index.ts:622
Check if the collection is currently loading more data
Returns
boolean
true if the collection has pending load more operations, false otherwise
Inherited from
CollectionImpl.isLoadingSubset
size
Get Signature
get size(): number;Defined in: packages/db/src/collection/index.ts:734
Get the current size of the collection (cached)
Returns
number
Inherited from
state
Get Signature
get state(): Map<TKey, WithVirtualProps<TOutput, TKey>>;Defined in: packages/db/src/collection/index.ts:1061
Gets the current state of the collection as a Map
Example
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"))
}Returns
Map<TKey, WithVirtualProps<TOutput, TKey>>
Map containing all items in the collection, with keys as identifiers
Inherited from
status
Get Signature
get status(): CollectionStatus;Defined in: packages/db/src/collection/index.ts:539
Gets the current status of the collection
Returns
Inherited from
subscriberCount
Get Signature
get subscriberCount(): number;Defined in: packages/db/src/collection/index.ts:547
Get the number of subscribers that ask for this collection's data. A live query that has no subscriber or preload of its own does not count.
Returns
number
Inherited from
CollectionImpl.subscriberCount
toArray
Get Signature
get toArray(): WithVirtualProps<TOutput, TKey>[];Defined in: packages/db/src/collection/index.ts:1091
Gets the current state of the collection as an Array
Returns
WithVirtualProps<TOutput, TKey>[]
An Array containing all items in the collection
Inherited from
Methods
_deferPublication()
_deferPublication(): PublicationDeferral;Defined in: packages/db/src/collection/index.ts:579
Defer subscriber events until a coherent multi-Collection commit ends.
Returns
PublicationDeferral
Inherited from
CollectionImpl._deferPublication
_deferSyncStart()
_deferSyncStart(): boolean;Defined in: packages/db/src/collection/index.ts:651
Internal
Returns
boolean
Inherited from
CollectionImpl._deferSyncStart
_hasHydratedKey()
_hasHydratedKey(key): boolean;Defined in: packages/db/src/collection/index.ts:646
Internal
Parameters
key
TKey
Returns
boolean
Inherited from
CollectionImpl._hasHydratedKey
_hasSubscriberOrPreload()
_hasSubscriberOrPreload(): boolean;Defined in: packages/db/src/collection/index.ts:690
Internal
Whether this Collection had a subscriber or a preload in this sync run.
Returns
boolean
Inherited from
CollectionImpl._hasSubscriberOrPreload
_markLayoutChange()
_markLayoutChange(): void;Defined in: packages/db/src/collection/index.ts:574
Mark the active sync transaction as layout-changing. Internal.
Returns
void
Inherited from
CollectionImpl._markLayoutChange
_markPreload()
_markPreload(): void;Defined in: packages/db/src/collection/index.ts:685
Internal
Record a preload without starting one, for a caller whose data request another promise answers, such as a DbClient stream for the same query. The request still counts: deferred acquisition may now resume.
Returns
void
Inherited from
_onCleanupStart()
_onCleanupStart(callback): () => void;Defined in: packages/db/src/collection/index.ts:636
Internal
Subscribe to the synchronous cleanup-start boundary.
Parameters
callback
() => void
Returns
(): void;Returns
void
Inherited from
CollectionImpl._onCleanupStart
_onFirstSubscriberOrPreload()
_onFirstSubscriberOrPreload(listener): () => void;Defined in: packages/db/src/collection/index.ts:695
Internal
Listen for the first subscriber or preload in this sync run.
Parameters
listener
() => void
Returns
(): void;Returns
void
Inherited from
CollectionImpl._onFirstSubscriberOrPreload
_resumeSyncStart()
_resumeSyncStart(): void;Defined in: packages/db/src/collection/index.ts:656
Internal
Returns
void
Inherited from
CollectionImpl._resumeSyncStart
_setTransactionScope()
_setTransactionScope(transactionScope): void;Defined in: packages/db/src/collection/index.ts:641
Internal
Parameters
transactionScope
Returns
void
Inherited from
CollectionImpl._setTransactionScope
_subscribeLayoutChanges()
_subscribeLayoutChanges(listener): () => void;Defined in: packages/db/src/collection/index.ts:569
Subscribe to layout-only publications. Internal observer channel.
Parameters
listener
() => void
Returns
(): void;Returns
void
Inherited from
CollectionImpl._subscribeLayoutChanges
_syncedRowMetadataKeysOutsideBase()
_syncedRowMetadataKeysOutsideBase(): TKey[];Defined in: packages/db/src/collection/index.ts:709
Internal
Applied metadata keys without a source row.
Returns
TKey[]
Inherited from
CollectionImpl._syncedRowMetadataKeysOutsideBase
[iterator]()
iterator: IterableIterator<[TKey, WithVirtualProps<T, TKey>]>;Defined in: packages/db/src/collection/index.ts:772
Get all entries (virtual derived state)
Returns
IterableIterator<[TKey, WithVirtualProps<T, TKey>]>
Inherited from
cleanup()
cleanup(): Promise<void>;Defined in: packages/db/src/collection/index.ts:1264
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.
Returns
Promise<void>
Inherited from
createIndex()
createIndex<TIndexType>(indexCallback, config): BaseIndex<TKey>;Defined in: packages/db/src/collection/index.ts:838
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.
Type Parameters
TIndexType
TIndexType extends IndexConstructor<TKey>
Parameters
indexCallback
(row) => any
Function that extracts the indexed value from each item
config
IndexOptions<TIndexType> = {}
Configuration including index type and type-specific options
Returns
BaseIndex<TKey>
The created index
Example
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)Inherited from
currentStateAsChanges()
currentStateAsChanges(options):
| void
| ChangeMessage<WithVirtualProps<T, TKey>, TKey>[];Defined in: packages/db/src/collection/index.ts:1130
Returns the current state of the collection as an array of changes
Parameters
options
CurrentStateAsChangesOptions = {}
Options including optional where filter
Returns
| void
| ChangeMessage<WithVirtualProps<T, TKey>, TKey>[]
An array of changes
Example
// 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')
})Inherited from
CollectionImpl.currentStateAsChanges
delete()
delete(keys, config?): Transaction<any>;Defined in: packages/db/src/collection/index.ts:1038
Deletes one or more items from the collection
Parameters
keys
Single key or array of keys to delete
TKey | TKey[]
config?
Optional configuration including metadata
Returns
Transaction<any>
A Transaction object representing the delete operation(s)
Examples
// 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)
}Inherited from
entries()
entries(): IterableIterator<[TKey, WithVirtualProps<T, TKey>]>;Defined in: packages/db/src/collection/index.ts:760
Get all entries (virtual derived state)
Returns
IterableIterator<[TKey, WithVirtualProps<T, TKey>]>
Inherited from
forEach()
forEach(callbackfn): void;Defined in: packages/db/src/collection/index.ts:781
Execute a callback for each entry in the collection
Parameters
callbackfn
(value, key, index) => void
Returns
void
Inherited from
get()
get(key):
| WithVirtualProps<T, TKey>
| undefined;Defined in: packages/db/src/collection/index.ts:720
Get the current value for a key (virtual derived state)
Parameters
key
TKey
Returns
| WithVirtualProps<T, TKey>
| undefined
Inherited from
getIndexMetadata()
getIndexMetadata(): CollectionIndexMetadata[];Defined in: packages/db/src/collection/index.ts:862
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.
Returns
Inherited from
CollectionImpl.getIndexMetadata
getKeyFromItem()
getKeyFromItem(item): TKey;Defined in: packages/db/src/collection/index.ts:812
Parameters
item
T
Returns
TKey
Inherited from
has()
has(key): boolean;Defined in: packages/db/src/collection/index.ts:727
Check if a key exists in the collection (virtual derived state)
Parameters
key
TKey
Returns
boolean
Inherited from
insert()
insert(data, config?):
| Transaction<Record<string, unknown>>
| Transaction<T>;Defined in: packages/db/src/collection/index.ts:925
Inserts one or more items into the collection
Parameters
data
TInsertInput | TInsertInput[]
config?
Optional configuration including metadata
Returns
| Transaction<Record<string, unknown>>
| Transaction<T>
A Transaction object representing the insert operation(s)
Throws
If the data fails schema validation
Examples
// 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)
}Inherited from
isReady()
isReady(): boolean;Defined in: packages/db/src/collection/index.ts:614
Check if the collection is ready for use Returns true if the collection has been marked as ready by its sync implementation
Returns
boolean
true if the collection is ready, false otherwise
Example
if (collection.isReady()) {
console.log('Collection is ready, data is available')
// Safe to access collection.state
} else {
console.log('Collection is still loading')
}Inherited from
keys()
keys(): IterableIterator<TKey>;Defined in: packages/db/src/collection/index.ts:741
Get all keys (virtual derived state)
Returns
IterableIterator<TKey>
Inherited from
map()
map<U>(callbackfn): U[];Defined in: packages/db/src/collection/index.ts:797
Create a new array with the results of calling a function for each entry in the collection
Type Parameters
U
U
Parameters
callbackfn
(value, key, index) => U
Returns
U[]
Inherited from
off()
off<T>(event, callback): void;Defined in: packages/db/src/collection/index.ts:1239
Unsubscribe from a collection event
Type Parameters
T
T extends
| "status:error"
| "status:idle"
| "status:loading"
| "status:ready"
| "status:cleaned-up"
| "status:change"
| "subscribers:change"
| "loadingSubset:change"
| "truncate"
| "index:added"
| "index:removed"
Parameters
event
T
callback
CollectionEventHandler<T>
Returns
void
Inherited from
on()
on<T>(event, callback): () => void;Defined in: packages/db/src/collection/index.ts:1219
Subscribe to a collection event
Type Parameters
T
T extends
| "status:error"
| "status:idle"
| "status:loading"
| "status:ready"
| "status:cleaned-up"
| "status:change"
| "subscribers:change"
| "loadingSubset:change"
| "truncate"
| "index:added"
| "index:removed"
Parameters
event
T
callback
CollectionEventHandler<T>
Returns
(): void;Returns
void
Inherited from
once()
once<T>(event, callback): () => void;Defined in: packages/db/src/collection/index.ts:1229
Subscribe to a collection event once
Type Parameters
T
T extends
| "status:error"
| "status:idle"
| "status:loading"
| "status:ready"
| "status:cleaned-up"
| "status:change"
| "subscribers:change"
| "loadingSubset:change"
| "truncate"
| "index:added"
| "index:removed"
Parameters
event
T
callback
CollectionEventHandler<T>
Returns
(): void;Returns
void
Inherited from
onFirstReady()
onFirstReady(callback): () => void;Defined in: packages/db/src/collection/index.ts:598
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.
Parameters
callback
() => void
Function to call when the collection first becomes ready
Returns
(): void;Returns
void
Example
collection.onFirstReady(() => {
console.log('Collection is ready for the first time')
// Safe to access collection.state now
})Inherited from
preload()
preload(): Promise<void>;Defined in: packages/db/src/collection/index.ts:664
Preload the collection data by starting sync if not already started Multiple concurrent calls will share the same promise
Returns
Promise<void>
Inherited from
removeIndex()
removeIndex(indexOrId): boolean;Defined in: packages/db/src/collection/index.ts:853
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.
Parameters
indexOrId
number | BaseIndex<TKey>
Returns
boolean
Inherited from
startSyncImmediate()
startSyncImmediate(): void;Defined in: packages/db/src/collection/index.ts:631
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.
Returns
void
Inherited from
CollectionImpl.startSyncImmediate
stateWhenReady()
stateWhenReady(): Promise<Map<TKey, WithVirtualProps<T, TKey>>>;Defined in: packages/db/src/collection/index.ts:1075
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
Returns
Promise<Map<TKey, WithVirtualProps<T, TKey>>>
Promise that resolves to a Map containing all items in the collection
Inherited from
subscribeChanges()
Call Signature
subscribeChanges(callback, options?): CollectionSubscription;Defined in: packages/db/src/collection/index.ts:1182
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.
Parameters
callback
(changes) => void
Function called when items change
options?
SubscribeChangesOptions<T, TKey>
Subscription options including includeInitialState and where filter
Returns
CollectionSubscription
Unsubscribe function - Call this to stop listening for changes
Examples
// 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))
})Inherited from
CollectionImpl.subscribeChanges
Call Signature
subscribeChanges(callback, options?): CollectionSubscription;Defined in: packages/db/src/collection/index.ts:1190
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.
Parameters
callback
Function called when items change
(changes) => void | (changes) => void
options?
SubscribeChangesOptions<T, TKey>
Subscription options including includeInitialState and where filter
Returns
CollectionSubscription
Unsubscribe function - Call this to stop listening for changes
Examples
// 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))
})Inherited from
CollectionImpl.subscribeChanges
toArrayWhenReady()
toArrayWhenReady(): Promise<WithVirtualProps<T, TKey>[]>;Defined in: packages/db/src/collection/index.ts:1101
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
Returns
Promise<WithVirtualProps<T, TKey>[]>
Promise that resolves to an Array containing all items in the collection
Inherited from
CollectionImpl.toArrayWhenReady
update()
Call Signature
update(key, callback): Transaction;Defined in: packages/db/src/collection/index.ts:970
Updates one or more items in the collection using a callback function
Parameters
key
TKey[]
callback
(drafts) => void
Returns
A Transaction object representing the update operation(s)
Throws
If the updated data fails schema validation
Examples
// 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)
}Inherited from
Call Signature
update(
keys,
config,
callback): Transaction;Defined in: packages/db/src/collection/index.ts:976
Updates one or more items in the collection using a callback function
Parameters
keys
TKey[]
Single key or array of keys to update
config
callback
(drafts) => void
Returns
A Transaction object representing the update operation(s)
Throws
If the updated data fails schema validation
Examples
// 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)
}Inherited from
Call Signature
update(id, callback): Transaction;Defined in: packages/db/src/collection/index.ts:983
Updates one or more items in the collection using a callback function
Parameters
id
TKey
callback
(draft) => void
Returns
A Transaction object representing the update operation(s)
Throws
If the updated data fails schema validation
Examples
// 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)
}Inherited from
Call Signature
update(
id,
config,
callback): Transaction;Defined in: packages/db/src/collection/index.ts:989
Updates one or more items in the collection using a callback function
Parameters
id
TKey
config
callback
(draft) => void
Returns
A Transaction object representing the update operation(s)
Throws
If the updated data fails schema validation
Examples
// 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)
}Inherited from
validateData()
validateData(
data,
type,
key?): T;Defined in: packages/db/src/collection/index.ts:876
Validates the data against the schema
Parameters
data
unknown
type
"insert" | "update"
key?
TKey
Returns
T
Inherited from
values()
values(): IterableIterator<WithVirtualProps<T, TKey>>;Defined in: packages/db/src/collection/index.ts:748
Get all values (virtual derived state)
Returns
IterableIterator<WithVirtualProps<T, TKey>>
Inherited from
waitFor()
waitFor<T>(event, timeout?): Promise<AllCollectionEvents[T]>;Defined in: packages/db/src/collection/index.ts:1249
Wait for a collection event
Type Parameters
T
T extends
| "status:error"
| "status:idle"
| "status:loading"
| "status:ready"
| "status:cleaned-up"
| "status:change"
| "subscribers:change"
| "loadingSubset:change"
| "truncate"
| "index:added"
| "index:removed"
Parameters
event
T
timeout?
number
Returns
Promise<AllCollectionEvents[T]>