--- id: CollectionImpl title: CollectionImpl --- # Class: CollectionImpl\ Defined in: [packages/db/src/collection.ts:204](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L204) ## Extended by - [`Collection`](../../interfaces/collection.md) ## Type Parameters • **T** *extends* `object` = `Record`\<`string`, `unknown`\> • **TKey** *extends* `string` \| `number` = `string` \| `number` • **TUtils** *extends* [`UtilsRecord`](../../type-aliases/utilsrecord.md) = \{\} • **TSchema** *extends* `StandardSchemaV1` = `StandardSchemaV1` • **TInsertInput** *extends* `object` = `T` ## Constructors ### new CollectionImpl() ```ts new CollectionImpl(config): CollectionImpl ``` Defined in: [packages/db/src/collection.ts:407](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L407) Creates a new Collection instance #### Parameters ##### config [`CollectionConfig`](../../interfaces/collectionconfig.md)\<`T`, `TKey`, `TSchema`, `TInsertInput`\> Configuration object for the collection #### Returns [`CollectionImpl`](../collectionimpl.md)\<`T`, `TKey`, `TUtils`, `TSchema`, `TInsertInput`\> #### Throws Error if sync config is missing ## Properties ### config ```ts config: CollectionConfig; ``` Defined in: [packages/db/src/collection.ts:211](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L211) *** ### id ```ts id: string; ``` Defined in: [packages/db/src/collection.ts:331](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L331) *** ### optimisticDeletes ```ts optimisticDeletes: Set; ``` Defined in: [packages/db/src/collection.ts:221](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L221) *** ### optimisticUpserts ```ts optimisticUpserts: Map; ``` Defined in: [packages/db/src/collection.ts:220](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L220) *** ### pendingSyncedTransactions ```ts pendingSyncedTransactions: PendingSyncedTransaction[] = []; ``` Defined in: [packages/db/src/collection.ts:215](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L215) *** ### syncedData ```ts syncedData: Map | SortedMap; ``` Defined in: [packages/db/src/collection.ts:216](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L216) *** ### syncedMetadata ```ts syncedMetadata: Map; ``` Defined in: [packages/db/src/collection.ts:217](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L217) *** ### transactions ```ts transactions: SortedMap>; ``` Defined in: [packages/db/src/collection.ts:214](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L214) *** ### utils ```ts utils: Record = {}; ``` Defined in: [packages/db/src/collection.ts:238](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L238) ## Accessors ### indexes #### Get Signature ```ts get indexes(): Map> ``` Defined in: [packages/db/src/collection.ts:1439](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1439) Get resolved indexes for query optimization ##### Returns `Map`\<`number`, [`BaseIndex`](../baseindex.md)\<`TKey`\>\> *** ### size #### Get Signature ```ts get size(): number ``` Defined in: [packages/db/src/collection.ts:995](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L995) Get the current size of the collection (cached) ##### Returns `number` *** ### state #### Get Signature ```ts get state(): Map ``` Defined in: [packages/db/src/collection.ts:2038](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2038) Gets the current state of the collection as a Map ##### Example ```ts 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`, `T`\> Map containing all items in the collection, with keys as identifiers *** ### status #### Get Signature ```ts get status(): CollectionStatus ``` Defined in: [packages/db/src/collection.ts:336](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L336) Gets the current status of the collection ##### Returns [`CollectionStatus`](../../type-aliases/collectionstatus.md) *** ### toArray #### Get Signature ```ts get toArray(): T[] ``` Defined in: [packages/db/src/collection.ts:2071](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2071) Gets the current state of the collection as an Array ##### Returns `T`[] An Array containing all items in the collection ## Methods ### \[iterator\]() ```ts iterator: IterableIterator<[TKey, T]> ``` Defined in: [packages/db/src/collection.ts:1046](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1046) Get all entries (virtual derived state) #### Returns `IterableIterator`\<\[`TKey`, `T`\]\> *** ### cleanup() ```ts cleanup(): Promise ``` Defined in: [packages/db/src/collection.ts:583](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L583) Clean up the collection by stopping sync and clearing data This can be called manually or automatically by garbage collection #### Returns `Promise`\<`void`\> *** ### commitPendingTransactions() ```ts commitPendingTransactions(): void ``` Defined in: [packages/db/src/collection.ts:1082](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1082) Attempts to commit pending synced transactions if there are no active transactions This method processes operations from pending transactions and applies them to the synced data #### Returns `void` *** ### createIndex() ```ts createIndex(indexCallback, config): IndexProxy ``` Defined in: [packages/db/src/collection.ts:1344](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1344) Creates an index on a collection for faster queries. Indexes significantly improve query performance by allowing binary search and range queries instead of full scans. #### Type Parameters • **TResolver** *extends* [`IndexResolver`](../../type-aliases/indexresolver.md)\<`TKey`\> = *typeof* [`BTreeIndex`](../btreeindex.md) The type of the index resolver (constructor or async loader) #### Parameters ##### indexCallback (`row`) => `any` Function that extracts the indexed value from each item ##### config [`IndexOptions`](../../interfaces/indexoptions.md)\<`TResolver`\> = `{}` Configuration including index type and type-specific options #### Returns [`IndexProxy`](../indexproxy.md)\<`TKey`\> An index proxy that provides access to the index when ready #### Example ```ts // Create a default B+ tree index const ageIndex = collection.createIndex((row) => row.age) // Create a ordered index with custom options const ageIndex = collection.createIndex((row) => row.age, { indexType: BTreeIndex, options: { compareFn: customComparator }, name: 'age_btree' }) // Create an async-loaded index const textIndex = collection.createIndex((row) => row.content, { indexType: async () => { const { FullTextIndex } = await import('./indexes/fulltext.js') return FullTextIndex }, options: { language: 'en' } }) ``` *** ### currentStateAsChanges() ```ts currentStateAsChanges(options): ChangeMessage[] ``` Defined in: [packages/db/src/collection.ts:2113](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2113) Returns the current state of the collection as an array of changes #### Parameters ##### options [`CurrentStateAsChangesOptions`](../../interfaces/currentstateaschangesoptions.md)\<`T`\> = `{}` Options including optional where filter #### Returns [`ChangeMessage`](../../interfaces/changemessage.md)\<`T`, `string` \| `number`\>[] An array of changes #### Example ```ts // 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') }) ``` *** ### delete() ```ts delete(keys, config?): Transaction ``` Defined in: [packages/db/src/collection.ts:1939](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1939) Deletes one or more items from the collection #### Parameters ##### keys Single key or array of keys to delete `TKey` | `TKey`[] ##### config? [`OperationConfig`](../../interfaces/operationconfig.md) Optional configuration including metadata #### Returns [`Transaction`](../transaction.md)\<`any`\> A Transaction object representing the delete operation(s) #### Examples ```ts // Delete a single item const tx = collection.delete("todo-1") await tx.isPersisted.promise ``` ```ts // Delete multiple items const tx = collection.delete(["todo-1", "todo-2"]) await tx.isPersisted.promise ``` ```ts // Delete with metadata const tx = collection.delete("todo-1", { metadata: { reason: "completed" } }) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.delete("item-1") await tx.isPersisted.promise console.log('Delete successful') } catch (error) { console.log('Delete failed:', error) } ``` *** ### entries() ```ts entries(): IterableIterator<[TKey, T]> ``` Defined in: [packages/db/src/collection.ts:1034](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1034) Get all entries (virtual derived state) #### Returns `IterableIterator`\<\[`TKey`, `T`\]\> *** ### forEach() ```ts forEach(callbackfn): void ``` Defined in: [packages/db/src/collection.ts:1055](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1055) Execute a callback for each entry in the collection #### Parameters ##### callbackfn (`value`, `key`, `index`) => `void` #### Returns `void` *** ### generateGlobalKey() ```ts generateGlobalKey(key, item): string ``` Defined in: [packages/db/src/collection.ts:1306](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1306) #### Parameters ##### key `any` ##### item `any` #### Returns `string` *** ### get() ```ts get(key): undefined | T ``` Defined in: [packages/db/src/collection.ts:959](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L959) Get the current value for a key (virtual derived state) #### Parameters ##### key `TKey` #### Returns `undefined` \| `T` *** ### getKeyFromItem() ```ts getKeyFromItem(item): TKey ``` Defined in: [packages/db/src/collection.ts:1302](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1302) #### Parameters ##### item `T` #### Returns `TKey` *** ### has() ```ts has(key): boolean ``` Defined in: [packages/db/src/collection.ts:977](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L977) Check if a key exists in the collection (virtual derived state) #### Parameters ##### key `TKey` #### Returns `boolean` *** ### insert() ```ts insert(data, config?): | Transaction> | Transaction ``` Defined in: [packages/db/src/collection.ts:1594](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1594) Inserts one or more items into the collection #### Parameters ##### data `TInsertInput` | `TInsertInput`[] ##### config? [`InsertConfig`](../../interfaces/insertconfig.md) Optional configuration including metadata #### Returns \| [`Transaction`](../transaction.md)\<`Record`\<`string`, `unknown`\>\> \| [`Transaction`](../transaction.md)\<`T`\> A Transaction object representing the insert operation(s) #### Throws If the data fails schema validation #### Examples ```ts // Insert a single todo (requires onInsert handler) const tx = collection.insert({ id: "1", text: "Buy milk", completed: false }) await tx.isPersisted.promise ``` ```ts // 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.isPersisted.promise ``` ```ts // Insert with metadata const tx = collection.insert({ id: "1", text: "Buy groceries" }, { metadata: { source: "mobile-app" } } ) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.insert({ id: "1", text: "New item" }) await tx.isPersisted.promise console.log('Insert successful') } catch (error) { console.log('Insert failed:', error) } ``` *** ### isReady() ```ts isReady(): boolean ``` Defined in: [packages/db/src/collection.ts:294](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L294) 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 ```ts if (collection.isReady()) { console.log('Collection is ready, data is available') // Safe to access collection.state } else { console.log('Collection is still loading') } ``` *** ### keys() ```ts keys(): IterableIterator ``` Defined in: [packages/db/src/collection.ts:1002](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1002) Get all keys (virtual derived state) #### Returns `IterableIterator`\<`TKey`\> *** ### map() ```ts map(callbackfn): U[] ``` Defined in: [packages/db/src/collection.ts:1067](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1067) Create a new array with the results of calling a function for each entry in the collection #### Type Parameters • **U** #### Parameters ##### callbackfn (`value`, `key`, `index`) => `U` #### Returns `U`[] *** ### onFirstReady() ```ts onFirstReady(callback): void ``` Defined in: [packages/db/src/collection.ts:272](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L272) Register a callback to be executed when the collection first becomes ready Useful for preloading collections #### Parameters ##### callback () => `void` Function to call when the collection first becomes ready #### Returns `void` #### Example ```ts collection.onFirstReady(() => { console.log('Collection is ready for the first time') // Safe to access collection.state now }) ``` *** ### onTransactionStateChange() ```ts onTransactionStateChange(): void ``` Defined in: [packages/db/src/collection.ts:2271](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2271) Trigger a recomputation when transactions change This method should be called by the Transaction class when state changes #### Returns `void` *** ### preload() ```ts preload(): Promise ``` Defined in: [packages/db/src/collection.ts:544](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L544) Preload the collection data by starting sync if not already started Multiple concurrent calls will share the same promise #### Returns `Promise`\<`void`\> *** ### startSyncImmediate() ```ts startSyncImmediate(): void ``` Defined in: [packages/db/src/collection.ts:450](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L450) Start sync immediately - internal method for compiled queries This bypasses lazy loading for special cases like live query results #### Returns `void` *** ### stateWhenReady() ```ts stateWhenReady(): Promise> ``` Defined in: [packages/db/src/collection.ts:2052](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2052) 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`, `T`\>\> Promise that resolves to a Map containing all items in the collection *** ### subscribeChanges() ```ts subscribeChanges(callback, options): () => void ``` Defined in: [packages/db/src/collection.ts:2158](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2158) Subscribe to changes in the collection #### Parameters ##### callback (`changes`) => `void` Function called when items change ##### options [`SubscribeChangesOptions`](../../interfaces/subscribechangesoptions.md)\<`T`\> = `{}` Subscription options including includeInitialState and where filter #### Returns `Function` Unsubscribe function - Call this to stop listening for changes ##### Returns `void` #### Examples ```ts // Basic subscription const unsubscribe = collection.subscribeChanges((changes) => { changes.forEach(change => { console.log(`${change.type}: ${change.key}`, change.value) }) }) // Later: unsubscribe() ``` ```ts // Include current state immediately const unsubscribe = collection.subscribeChanges((changes) => { updateUI(changes) }, { includeInitialState: true }) ``` ```ts // Subscribe only to changes matching a condition const unsubscribe = collection.subscribeChanges((changes) => { updateUI(changes) }, { includeInitialState: true, where: (row) => row.status === 'active' }) ``` ```ts // Subscribe using a pre-compiled expression const unsubscribe = collection.subscribeChanges((changes) => { updateUI(changes) }, { includeInitialState: true, whereExpression: eq(row.status, 'active') }) ``` *** ### subscribeChangesKey() ```ts subscribeChangesKey( key, listener, __namedParameters): () => void ``` Defined in: [packages/db/src/collection.ts:2197](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2197) Subscribe to changes for a specific key #### Parameters ##### key `TKey` ##### listener [`ChangeListener`](../../type-aliases/changelistener.md)\<`T`, `TKey`\> ##### \_\_namedParameters ###### includeInitialState? `boolean` = `false` #### Returns `Function` ##### Returns `void` *** ### toArrayWhenReady() ```ts toArrayWhenReady(): Promise ``` Defined in: [packages/db/src/collection.ts:2081](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2081) 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`\<`T`[]\> Promise that resolves to an Array containing all items in the collection *** ### update() #### Call Signature ```ts update(key, callback): Transaction ``` Defined in: [packages/db/src/collection.ts:1725](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1725) Updates one or more items in the collection using a callback function ##### Type Parameters • **TItem** *extends* `object` = `T` ##### Parameters ###### key `unknown`[] ###### callback (`drafts`) => `void` ##### Returns [`Transaction`](../transaction.md) A Transaction object representing the update operation(s) ##### Throws If the updated data fails schema validation ##### Examples ```ts // Update single item by key const tx = collection.update("todo-1", (draft) => { draft.completed = true }) await tx.isPersisted.promise ``` ```ts // Update multiple items const tx = collection.update(["todo-1", "todo-2"], (drafts) => { drafts.forEach(draft => { draft.completed = true }) }) await tx.isPersisted.promise ``` ```ts // Update with metadata const tx = collection.update("todo-1", { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" } ) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.update("item-1", draft => { draft.value = "new" }) await tx.isPersisted.promise console.log('Update successful') } catch (error) { console.log('Update failed:', error) } ``` #### Call Signature ```ts update( keys, config, callback): Transaction ``` Defined in: [packages/db/src/collection.ts:1731](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1731) Updates one or more items in the collection using a callback function ##### Type Parameters • **TItem** *extends* `object` = `T` ##### Parameters ###### keys `unknown`[] Single key or array of keys to update ###### config [`OperationConfig`](../../interfaces/operationconfig.md) ###### callback (`drafts`) => `void` ##### Returns [`Transaction`](../transaction.md) A Transaction object representing the update operation(s) ##### Throws If the updated data fails schema validation ##### Examples ```ts // Update single item by key const tx = collection.update("todo-1", (draft) => { draft.completed = true }) await tx.isPersisted.promise ``` ```ts // Update multiple items const tx = collection.update(["todo-1", "todo-2"], (drafts) => { drafts.forEach(draft => { draft.completed = true }) }) await tx.isPersisted.promise ``` ```ts // Update with metadata const tx = collection.update("todo-1", { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" } ) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.update("item-1", draft => { draft.value = "new" }) await tx.isPersisted.promise console.log('Update successful') } catch (error) { console.log('Update failed:', error) } ``` #### Call Signature ```ts update(id, callback): Transaction ``` Defined in: [packages/db/src/collection.ts:1738](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1738) Updates one or more items in the collection using a callback function ##### Type Parameters • **TItem** *extends* `object` = `T` ##### Parameters ###### id `unknown` ###### callback (`draft`) => `void` ##### Returns [`Transaction`](../transaction.md) A Transaction object representing the update operation(s) ##### Throws If the updated data fails schema validation ##### Examples ```ts // Update single item by key const tx = collection.update("todo-1", (draft) => { draft.completed = true }) await tx.isPersisted.promise ``` ```ts // Update multiple items const tx = collection.update(["todo-1", "todo-2"], (drafts) => { drafts.forEach(draft => { draft.completed = true }) }) await tx.isPersisted.promise ``` ```ts // Update with metadata const tx = collection.update("todo-1", { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" } ) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.update("item-1", draft => { draft.value = "new" }) await tx.isPersisted.promise console.log('Update successful') } catch (error) { console.log('Update failed:', error) } ``` #### Call Signature ```ts update( id, config, callback): Transaction ``` Defined in: [packages/db/src/collection.ts:1744](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1744) Updates one or more items in the collection using a callback function ##### Type Parameters • **TItem** *extends* `object` = `T` ##### Parameters ###### id `unknown` ###### config [`OperationConfig`](../../interfaces/operationconfig.md) ###### callback (`draft`) => `void` ##### Returns [`Transaction`](../transaction.md) A Transaction object representing the update operation(s) ##### Throws If the updated data fails schema validation ##### Examples ```ts // Update single item by key const tx = collection.update("todo-1", (draft) => { draft.completed = true }) await tx.isPersisted.promise ``` ```ts // Update multiple items const tx = collection.update(["todo-1", "todo-2"], (drafts) => { drafts.forEach(draft => { draft.completed = true }) }) await tx.isPersisted.promise ``` ```ts // Update with metadata const tx = collection.update("todo-1", { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" } ) await tx.isPersisted.promise ``` ```ts // Handle errors try { const tx = collection.update("item-1", draft => { draft.value = "new" }) await tx.isPersisted.promise console.log('Update successful') } catch (error) { console.log('Update failed:', error) } ``` *** ### values() ```ts values(): IterableIterator ``` Defined in: [packages/db/src/collection.ts:1022](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1022) Get all values (virtual derived state) #### Returns `IterableIterator`\<`T`\>