Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

collection.md

1,462 lines29.7 KB

1---
2id: Collection
3title: Collection
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8# Interface: Collection\<T, TKey, TUtils, TSchema, TInsertInput\>
9​
10Defined in: [packages/db/src/collection.ts:77](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L77)
11​
12Enhanced Collection interface that includes both data type T and utilities TUtils
13​
14## Extends
15​
16- [`CollectionImpl`](../../classes/collectionimpl.md)\<`T`, `TKey`, `TUtils`, `TSchema`, `TInsertInput`\>
17​
18## Type Parameters
19​
20• **T** *extends* `object` = `Record`\<`string`, `unknown`\>
21​
22The type of items in the collection
23​
24• **TKey** *extends* `string` \| `number` = `string` \| `number`
25​
26The type of the key for the collection
27​
28• **TUtils** *extends* [`UtilsRecord`](../../type-aliases/utilsrecord.md) = \{\}
29​
30The utilities record type
31​
32• **TSchema** *extends* `StandardSchemaV1` = `StandardSchemaV1`
33​
34• **TInsertInput** *extends* `object` = `T`
35​
36The type for insert operations (can be different from T for schemas with defaults)
37​
38## Properties
39​
40### config
41​
42```ts
43config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
44```
45​
46Defined in: [packages/db/src/collection.ts:211](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L211)
47​
48#### Inherited from
49​
50[`CollectionImpl`](../../classes/collectionimpl.md).[`config`](../../classes/CollectionImpl.md#config-1)
51​
52***
53​
54### id
55​
56```ts
57id: string;
58```
59​
60Defined in: [packages/db/src/collection.ts:331](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L331)
61​
62#### Inherited from
63​
64[`CollectionImpl`](../../classes/collectionimpl.md).[`id`](../../classes/CollectionImpl.md#id)
65​
66***
67​
68### optimisticDeletes
69​
70```ts
71optimisticDeletes: Set<TKey>;
72```
73​
74Defined in: [packages/db/src/collection.ts:221](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L221)
75​
76#### Inherited from
77​
78[`CollectionImpl`](../../classes/collectionimpl.md).[`optimisticDeletes`](../../classes/CollectionImpl.md#optimisticdeletes)
79​
80***
81​
82### optimisticUpserts
83​
84```ts
85optimisticUpserts: Map<TKey, T>;
86```
87​
88Defined in: [packages/db/src/collection.ts:220](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L220)
89​
90#### Inherited from
91​
92[`CollectionImpl`](../../classes/collectionimpl.md).[`optimisticUpserts`](../../classes/CollectionImpl.md#optimisticupserts)
93​
94***
95​
96### pendingSyncedTransactions
97​
98```ts
99pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
100```
101​
102Defined in: [packages/db/src/collection.ts:215](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L215)
103​
104#### Inherited from
105​
106[`CollectionImpl`](../../classes/collectionimpl.md).[`pendingSyncedTransactions`](../../classes/CollectionImpl.md#pendingsyncedtransactions)
107​
108***
109​
110### syncedData
111​
112```ts
113syncedData:
114 | Map<TKey, T>
115| SortedMap<TKey, T>;
116```
117​
118Defined in: [packages/db/src/collection.ts:216](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L216)
119​
120#### Inherited from
121​
122[`CollectionImpl`](../../classes/collectionimpl.md).[`syncedData`](../../classes/CollectionImpl.md#synceddata)
123​
124***
125​
126### syncedMetadata
127​
128```ts
129syncedMetadata: Map<TKey, unknown>;
130```
131​
132Defined in: [packages/db/src/collection.ts:217](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L217)
133​
134#### Inherited from
135​
136[`CollectionImpl`](../../classes/collectionimpl.md).[`syncedMetadata`](../../classes/CollectionImpl.md#syncedmetadata)
137​
138***
139​
140### transactions
141​
142```ts
143transactions: SortedMap<string, Transaction<any>>;
144```
145​
146Defined in: [packages/db/src/collection.ts:214](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L214)
147​
148#### Inherited from
149​
150[`CollectionImpl`](../../classes/collectionimpl.md).[`transactions`](../../classes/CollectionImpl.md#transactions)
151​
152***
153​
154### utils
155​
156```ts
157readonly utils: TUtils;
158```
159​
160Defined in: [packages/db/src/collection.ts:84](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L84)
161​
162#### Overrides
163​
164[`CollectionImpl`](../../classes/collectionimpl.md).[`utils`](../../classes/CollectionImpl.md#utils)
165​
166## Accessors
167​
168### indexes
169​
170#### Get Signature
171​
172```ts
173get indexes(): Map<number, BaseIndex<TKey>>
174```
175​
176Defined in: [packages/db/src/collection.ts:1439](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1439)
177​
178Get resolved indexes for query optimization
179​
180##### Returns
181​
182`Map`\<`number`, [`BaseIndex`](../../classes/baseindex.md)\<`TKey`\>\>
183​
184#### Inherited from
185​
186[`CollectionImpl`](../../classes/collectionimpl.md).[`indexes`](../../classes/CollectionImpl.md#indexes)
187​
188***
189​
190### size
191​
192#### Get Signature
193​
194```ts
195get size(): number
196```
197​
198Defined in: [packages/db/src/collection.ts:995](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L995)
199​
200Get the current size of the collection (cached)
201​
202##### Returns
203​
204`number`
205​
206#### Inherited from
207​
208[`CollectionImpl`](../../classes/collectionimpl.md).[`size`](../../classes/CollectionImpl.md#size)
209​
210***
211​
212### state
213​
214#### Get Signature
215​
216```ts
217get state(): Map<TKey, T>
218```
219​
220Defined in: [packages/db/src/collection.ts:2038](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2038)
221​
222Gets the current state of the collection as a Map
223​
224##### Example
225​
226```ts
227const itemsMap = collection.state
228console.log(`Collection has ${itemsMap.size} items`)
229​
230for (const [key, item] of itemsMap) {
231 console.log(`${key}: ${item.title}`)
233​
234// Check if specific item exists
235if (itemsMap.has("todo-1")) {
236 console.log("Todo 1 exists:", itemsMap.get("todo-1"))
238```
239​
240##### Returns
241​
242`Map`\<`TKey`, `T`\>
243​
244Map containing all items in the collection, with keys as identifiers
245​
246#### Inherited from
247​
248[`CollectionImpl`](../../classes/collectionimpl.md).[`state`](../../classes/CollectionImpl.md#state)
249​
250***
251​
252### status
253​
254#### Get Signature
255​
256```ts
257get status(): CollectionStatus
258```
259​
260Defined in: [packages/db/src/collection.ts:336](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L336)
261​
262Gets the current status of the collection
263​
264##### Returns
265​
266[`CollectionStatus`](../../type-aliases/collectionstatus.md)
267​
268#### Inherited from
269​
270[`CollectionImpl`](../../classes/collectionimpl.md).[`status`](../../classes/CollectionImpl.md#status)
271​
272***
273​
274### toArray
275​
276#### Get Signature
277​
278```ts
279get toArray(): T[]
280```
281​
282Defined in: [packages/db/src/collection.ts:2071](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2071)
283​
284Gets the current state of the collection as an Array
285​
286##### Returns
287​
288`T`[]
289​
290An Array containing all items in the collection
291​
292#### Inherited from
293​
294[`CollectionImpl`](../../classes/collectionimpl.md).[`toArray`](../../classes/CollectionImpl.md#toarray)
295​
296## Methods
297​
298### \[iterator\]()
299​
300```ts
301iterator: IterableIterator<[TKey, T]>
302```
303​
304Defined in: [packages/db/src/collection.ts:1046](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1046)
305​
306Get all entries (virtual derived state)
307​
308#### Returns
309​
310`IterableIterator`\<\[`TKey`, `T`\]\>
311​
312#### Inherited from
313​
314[`CollectionImpl`](../../classes/collectionimpl.md).[`[iterator]`](../../classes/CollectionImpl.md#iterator)
315​
316***
317​
318### cleanup()
319​
320```ts
321cleanup(): Promise<void>
322```
323​
324Defined in: [packages/db/src/collection.ts:583](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L583)
325​
326Clean up the collection by stopping sync and clearing data
327This can be called manually or automatically by garbage collection
328​
329#### Returns
330​
331`Promise`\<`void`\>
332​
333#### Inherited from
334​
335[`CollectionImpl`](../../classes/collectionimpl.md).[`cleanup`](../../classes/CollectionImpl.md#cleanup)
336​
337***
338​
339### commitPendingTransactions()
340​
341```ts
342commitPendingTransactions(): void
343```
344​
345Defined in: [packages/db/src/collection.ts:1082](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1082)
346​
347Attempts to commit pending synced transactions if there are no active transactions
348This method processes operations from pending transactions and applies them to the synced data
349​
350#### Returns
351​
352`void`
353​
354#### Inherited from
355​
356[`CollectionImpl`](../../classes/collectionimpl.md).[`commitPendingTransactions`](../../classes/CollectionImpl.md#commitpendingtransactions)
357​
358***
359​
360### createIndex()
361​
362```ts
363createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
364```
365​
366Defined in: [packages/db/src/collection.ts:1344](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1344)
367​
368Creates an index on a collection for faster queries.
369Indexes significantly improve query performance by allowing binary search
370and range queries instead of full scans.
371​
372#### Type Parameters
373​
374• **TResolver** *extends* [`IndexResolver`](../../type-aliases/indexresolver.md)\<`TKey`\> = *typeof* [`BTreeIndex`](../../classes/btreeindex.md)
375​
376The type of the index resolver (constructor or async loader)
377​
378#### Parameters
379​
380##### indexCallback
381​
382(`row`) => `any`
383​
384Function that extracts the indexed value from each item
385​
386##### config
387​
388[`IndexOptions`](../indexoptions.md)\<`TResolver`\> = `{}`
389​
390Configuration including index type and type-specific options
391​
392#### Returns
393​
394[`IndexProxy`](../../classes/indexproxy.md)\<`TKey`\>
395​
396An index proxy that provides access to the index when ready
397​
398#### Example
399​
400```ts
401// Create a default B+ tree index
402const ageIndex = collection.createIndex((row) => row.age)
403​
404// Create a ordered index with custom options
405const ageIndex = collection.createIndex((row) => row.age, {
406 indexType: BTreeIndex,
407 options: { compareFn: customComparator },
408 name: 'age_btree'
409})
410​
411// Create an async-loaded index
412const textIndex = collection.createIndex((row) => row.content, {
413 indexType: async () => {
414 const { FullTextIndex } = await import('./indexes/fulltext.js')
415 return FullTextIndex
416 },
417 options: { language: 'en' }
418})
419```
420​
421#### Inherited from
422​
423[`CollectionImpl`](../../classes/collectionimpl.md).[`createIndex`](../../classes/CollectionImpl.md#createindex)
424​
425***
426​
427### currentStateAsChanges()
428​
429```ts
430currentStateAsChanges(options): ChangeMessage<T, string | number>[]
431```
432​
433Defined in: [packages/db/src/collection.ts:2113](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2113)
434​
435Returns the current state of the collection as an array of changes
436​
437#### Parameters
438​
439##### options
440​
441[`CurrentStateAsChangesOptions`](../currentstateaschangesoptions.md)\<`T`\> = `{}`
442​
443Options including optional where filter
444​
445#### Returns
446​
447[`ChangeMessage`](../changemessage.md)\<`T`, `string` \| `number`\>[]
448​
449An array of changes
450​
451#### Example
452​
453```ts
454// Get all items as changes
455const allChanges = collection.currentStateAsChanges()
456​
457// Get only items matching a condition
458const activeChanges = collection.currentStateAsChanges({
459 where: (row) => row.status === 'active'
460})
461​
462// Get only items using a pre-compiled expression
463const activeChanges = collection.currentStateAsChanges({
464 whereExpression: eq(row.status, 'active')
465})
466```
467​
468#### Inherited from
469​
470[`CollectionImpl`](../../classes/collectionimpl.md).[`currentStateAsChanges`](../../classes/CollectionImpl.md#currentstateaschanges)
471​
472***
473​
474### delete()
475​
476```ts
477delete(keys, config?): Transaction<any>
478```
479​
480Defined in: [packages/db/src/collection.ts:1939](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1939)
481​
482Deletes one or more items from the collection
483​
484#### Parameters
485​
486##### keys
487​
488Single key or array of keys to delete
489​
490`TKey` | `TKey`[]
491​
492##### config?
493​
494[`OperationConfig`](../operationconfig.md)
495​
496Optional configuration including metadata
497​
498#### Returns
499​
500[`Transaction`](../../classes/transaction.md)\<`any`\>
501​
502A Transaction object representing the delete operation(s)
503​
504#### Examples
505​
506```ts
507// Delete a single item
508const tx = collection.delete("todo-1")
509await tx.isPersisted.promise
510```
511​
512```ts
513// Delete multiple items
514const tx = collection.delete(["todo-1", "todo-2"])
515await tx.isPersisted.promise
516```
517​
518```ts
519// Delete with metadata
520const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
521await tx.isPersisted.promise
522```
523​
524```ts
525// Handle errors
526try {
527 const tx = collection.delete("item-1")
528 await tx.isPersisted.promise
529 console.log('Delete successful')
530} catch (error) {
531 console.log('Delete failed:', error)
533```
534​
535#### Inherited from
536​
537[`CollectionImpl`](../../classes/collectionimpl.md).[`delete`](../../classes/CollectionImpl.md#delete)
538​
539***
540​
541### entries()
542​
543```ts
544entries(): IterableIterator<[TKey, T]>
545```
546​
547Defined in: [packages/db/src/collection.ts:1034](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1034)
548​
549Get all entries (virtual derived state)
550​
551#### Returns
552​
553`IterableIterator`\<\[`TKey`, `T`\]\>
554​
555#### Inherited from
556​
557[`CollectionImpl`](../../classes/collectionimpl.md).[`entries`](../../classes/CollectionImpl.md#entries)
558​
559***
560​
561### forEach()
562​
563```ts
564forEach(callbackfn): void
565```
566​
567Defined in: [packages/db/src/collection.ts:1055](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1055)
568​
569Execute a callback for each entry in the collection
570​
571#### Parameters
572​
573##### callbackfn
574​
575(`value`, `key`, `index`) => `void`
576​
577#### Returns
578​
579`void`
580​
581#### Inherited from
582​
583[`CollectionImpl`](../../classes/collectionimpl.md).[`forEach`](../../classes/CollectionImpl.md#foreach)
584​
585***
586​
587### generateGlobalKey()
588​
589```ts
590generateGlobalKey(key, item): string
591```
592​
593Defined in: [packages/db/src/collection.ts:1306](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1306)
594​
595#### Parameters
596​
597##### key
598​
599`any`
600​
601##### item
602​
603`any`
604​
605#### Returns
606​
607`string`
608​
609#### Inherited from
610​
611[`CollectionImpl`](../../classes/collectionimpl.md).[`generateGlobalKey`](../../classes/CollectionImpl.md#generateglobalkey)
612​
613***
614​
615### get()
616​
617```ts
618get(key): undefined | T
619```
620​
621Defined in: [packages/db/src/collection.ts:959](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L959)
622​
623Get the current value for a key (virtual derived state)
624​
625#### Parameters
626​
627##### key
628​
629`TKey`
630​
631#### Returns
632​
633`undefined` \| `T`
634​
635#### Inherited from
636​
637[`CollectionImpl`](../../classes/collectionimpl.md).[`get`](../../classes/CollectionImpl.md#get)
638​
639***
640​
641### getKeyFromItem()
642​
643```ts
644getKeyFromItem(item): TKey
645```
646​
647Defined in: [packages/db/src/collection.ts:1302](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1302)
648​
649#### Parameters
650​
651##### item
652​
653`T`
654​
655#### Returns
656​
657`TKey`
658​
659#### Inherited from
660​
661[`CollectionImpl`](../../classes/collectionimpl.md).[`getKeyFromItem`](../../classes/CollectionImpl.md#getkeyfromitem)
662​
663***
664​
665### has()
666​
667```ts
668has(key): boolean
669```
670​
671Defined in: [packages/db/src/collection.ts:977](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L977)
672​
673Check if a key exists in the collection (virtual derived state)
674​
675#### Parameters
676​
677##### key
678​
679`TKey`
680​
681#### Returns
682​
683`boolean`
684​
685#### Inherited from
686​
687[`CollectionImpl`](../../classes/collectionimpl.md).[`has`](../../classes/CollectionImpl.md#has)
688​
689***
690​
691### insert()
692​
693```ts
694insert(data, config?):
695 | Transaction<Record<string, unknown>>
696| Transaction<T>
697```
698​
699Defined in: [packages/db/src/collection.ts:1594](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1594)
700​
701Inserts one or more items into the collection
702​
703#### Parameters
704​
705##### data
706​
707`TInsertInput` | `TInsertInput`[]
708​
709##### config?
710​
711[`InsertConfig`](../insertconfig.md)
712​
713Optional configuration including metadata
714​
715#### Returns
716​
717 \| [`Transaction`](../../classes/transaction.md)\<`Record`\<`string`, `unknown`\>\>
718 \| [`Transaction`](../../classes/transaction.md)\<`T`\>
719​
720A Transaction object representing the insert operation(s)
721​
722#### Throws
723​
724If the data fails schema validation
725​
726#### Examples
727​
728```ts
729// Insert a single todo (requires onInsert handler)
730const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
731await tx.isPersisted.promise
732```
733​
734```ts
735// Insert multiple todos at once
736const tx = collection.insert([
737 { id: "1", text: "Buy milk", completed: false },
738 { id: "2", text: "Walk dog", completed: true }
739])
740await tx.isPersisted.promise
741```
742​
743```ts
744// Insert with metadata
745const tx = collection.insert({ id: "1", text: "Buy groceries" },
746 { metadata: { source: "mobile-app" } }
748await tx.isPersisted.promise
749```
750​
751```ts
752// Handle errors
753try {
754 const tx = collection.insert({ id: "1", text: "New item" })
755 await tx.isPersisted.promise
756 console.log('Insert successful')
757} catch (error) {
758 console.log('Insert failed:', error)
760```
761​
762#### Inherited from
763​
764[`CollectionImpl`](../../classes/collectionimpl.md).[`insert`](../../classes/CollectionImpl.md#insert)
765​
766***
767​
768### isReady()
769​
770```ts
771isReady(): boolean
772```
773​
774Defined in: [packages/db/src/collection.ts:294](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L294)
775​
776Check if the collection is ready for use
777Returns true if the collection has been marked as ready by its sync implementation
778​
779#### Returns
780​
781`boolean`
782​
783true if the collection is ready, false otherwise
784​
785#### Example
786​
787```ts
788if (collection.isReady()) {
789 console.log('Collection is ready, data is available')
790 // Safe to access collection.state
791} else {
792 console.log('Collection is still loading')
794```
795​
796#### Inherited from
797​
798[`CollectionImpl`](../../classes/collectionimpl.md).[`isReady`](../../classes/CollectionImpl.md#isready)
799​
800***
801​
802### keys()
803​
804```ts
805keys(): IterableIterator<TKey>
806```
807​
808Defined in: [packages/db/src/collection.ts:1002](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1002)
809​
810Get all keys (virtual derived state)
811​
812#### Returns
813​
814`IterableIterator`\<`TKey`\>
815​
816#### Inherited from
817​
818[`CollectionImpl`](../../classes/collectionimpl.md).[`keys`](../../classes/CollectionImpl.md#keys-1)
819​
820***
821​
822### map()
823​
824```ts
825map<U>(callbackfn): U[]
826```
827​
828Defined in: [packages/db/src/collection.ts:1067](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1067)
829​
830Create a new array with the results of calling a function for each entry in the collection
831​
832#### Type Parameters
833​
834• **U**
835​
836#### Parameters
837​
838##### callbackfn
839​
840(`value`, `key`, `index`) => `U`
841​
842#### Returns
843​
844`U`[]
845​
846#### Inherited from
847​
848[`CollectionImpl`](../../classes/collectionimpl.md).[`map`](../../classes/CollectionImpl.md#map)
849​
850***
851​
852### onFirstReady()
853​
854```ts
855onFirstReady(callback): void
856```
857​
858Defined in: [packages/db/src/collection.ts:272](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L272)
859​
860Register a callback to be executed when the collection first becomes ready
861Useful for preloading collections
862​
863#### Parameters
864​
865##### callback
866​
867() => `void`
868​
869Function to call when the collection first becomes ready
870​
871#### Returns
872​
873`void`
874​
875#### Example
876​
877```ts
878collection.onFirstReady(() => {
879 console.log('Collection is ready for the first time')
880 // Safe to access collection.state now
881})
882```
883​
884#### Inherited from
885​
886[`CollectionImpl`](../../classes/collectionimpl.md).[`onFirstReady`](../../classes/CollectionImpl.md#onfirstready)
887​
888***
889​
890### onTransactionStateChange()
891​
892```ts
893onTransactionStateChange(): void
894```
895​
896Defined in: [packages/db/src/collection.ts:2271](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2271)
897​
898Trigger a recomputation when transactions change
899This method should be called by the Transaction class when state changes
900​
901#### Returns
902​
903`void`
904​
905#### Inherited from
906​
907[`CollectionImpl`](../../classes/collectionimpl.md).[`onTransactionStateChange`](../../classes/CollectionImpl.md#ontransactionstatechange)
908​
909***
910​
911### preload()
912​
913```ts
914preload(): Promise<void>
915```
916​
917Defined in: [packages/db/src/collection.ts:544](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L544)
918​
919Preload the collection data by starting sync if not already started
920Multiple concurrent calls will share the same promise
921​
922#### Returns
923​
924`Promise`\<`void`\>
925​
926#### Inherited from
927​
928[`CollectionImpl`](../../classes/collectionimpl.md).[`preload`](../../classes/CollectionImpl.md#preload)
929​
930***
931​
932### startSyncImmediate()
933​
934```ts
935startSyncImmediate(): void
936```
937​
938Defined in: [packages/db/src/collection.ts:450](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L450)
939​
940Start sync immediately - internal method for compiled queries
941This bypasses lazy loading for special cases like live query results
942​
943#### Returns
944​
945`void`
946​
947#### Inherited from
948​
949[`CollectionImpl`](../../classes/collectionimpl.md).[`startSyncImmediate`](../../classes/CollectionImpl.md#startsyncimmediate)
950​
951***
952​
953### stateWhenReady()
954​
955```ts
956stateWhenReady(): Promise<Map<TKey, T>>
957```
958​
959Defined in: [packages/db/src/collection.ts:2052](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2052)
960​
961Gets the current state of the collection as a Map, but only resolves when data is available
962Waits for the first sync commit to complete before resolving
963​
964#### Returns
965​
966`Promise`\<`Map`\<`TKey`, `T`\>\>
967​
968Promise that resolves to a Map containing all items in the collection
969​
970#### Inherited from
971​
972[`CollectionImpl`](../../classes/collectionimpl.md).[`stateWhenReady`](../../classes/CollectionImpl.md#statewhenready)
973​
974***
975​
976### subscribeChanges()
977​
978```ts
979subscribeChanges(callback, options): () => void
980```
981​
982Defined in: [packages/db/src/collection.ts:2158](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2158)
983​
984Subscribe to changes in the collection
985​
986#### Parameters
987​
988##### callback
989​
990(`changes`) => `void`
991​
992Function called when items change
993​
994##### options
995​
996[`SubscribeChangesOptions`](../subscribechangesoptions.md)\<`T`\> = `{}`
997​
998Subscription options including includeInitialState and where filter
999​
1000#### Returns
1001​
1002`Function`
1003​
1004Unsubscribe function - Call this to stop listening for changes
1005​
1006##### Returns
1007​
1008`void`
1009​
1010#### Examples
1011​
1012```ts
1013// Basic subscription
1014const unsubscribe = collection.subscribeChanges((changes) => {
1015 changes.forEach(change => {
1016 console.log(`${change.type}: ${change.key}`, change.value)
1017 })
1019​
1020// Later: unsubscribe()
1021```
1022​
1023```ts
1024// Include current state immediately
1025const unsubscribe = collection.subscribeChanges((changes) => {
1026 updateUI(changes)
1027}, { includeInitialState: true })
1028```
1029​
1030```ts
1031// Subscribe only to changes matching a condition
1032const unsubscribe = collection.subscribeChanges((changes) => {
1033 updateUI(changes)
1034}, {
1035 includeInitialState: true,
1036 where: (row) => row.status === 'active'
1038```
1039​
1040```ts
1041// Subscribe using a pre-compiled expression
1042const unsubscribe = collection.subscribeChanges((changes) => {
1043 updateUI(changes)
1044}, {
1045 includeInitialState: true,
1046 whereExpression: eq(row.status, 'active')
1048```
1049​
1050#### Inherited from
1051​
1052[`CollectionImpl`](../../classes/collectionimpl.md).[`subscribeChanges`](../../classes/CollectionImpl.md#subscribechanges)
1053​
1054***
1055​
1056### subscribeChangesKey()
1057​
1058```ts
1059subscribeChangesKey(
1060 key,
1061 listener,
1062 __namedParameters): () => void
1063```
1064​
1065Defined in: [packages/db/src/collection.ts:2197](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2197)
1066​
1067Subscribe to changes for a specific key
1068​
1069#### Parameters
1070​
1071##### key
1072​
1073`TKey`
1074​
1075##### listener
1076​
1077[`ChangeListener`](../../type-aliases/changelistener.md)\<`T`, `TKey`\>
1078​
1079##### \_\_namedParameters
1080​
1081###### includeInitialState?
1082​
1083`boolean` = `false`
1084​
1085#### Returns
1086​
1087`Function`
1088​
1089##### Returns
1090​
1091`void`
1092​
1093#### Inherited from
1094​
1095[`CollectionImpl`](../../classes/collectionimpl.md).[`subscribeChangesKey`](../../classes/CollectionImpl.md#subscribechangeskey)
1096​
1097***
1098​
1099### toArrayWhenReady()
1100​
1101```ts
1102toArrayWhenReady(): Promise<T[]>
1103```
1104​
1105Defined in: [packages/db/src/collection.ts:2081](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L2081)
1106​
1107Gets the current state of the collection as an Array, but only resolves when data is available
1108Waits for the first sync commit to complete before resolving
1109​
1110#### Returns
1111​
1112`Promise`\<`T`[]\>
1113​
1114Promise that resolves to an Array containing all items in the collection
1115​
1116#### Inherited from
1117​
1118[`CollectionImpl`](../../classes/collectionimpl.md).[`toArrayWhenReady`](../../classes/CollectionImpl.md#toarraywhenready)
1119​
1120***
1121​
1122### update()
1123​
1124#### Call Signature
1125​
1126```ts
1127update<TItem>(key, callback): Transaction
1128```
1129​
1130Defined in: [packages/db/src/collection.ts:1725](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1725)
1131​
1132Updates one or more items in the collection using a callback function
1133​
1134##### Type Parameters
1135​
1136• **TItem** *extends* `object` = `T`
1137​
1138##### Parameters
1139​
1140###### key
1141​
1142`unknown`[]
1143​
1144###### callback
1145​
1146(`drafts`) => `void`
1147​
1148##### Returns
1149​
1150[`Transaction`](../../classes/transaction.md)
1151​
1152A Transaction object representing the update operation(s)
1153​
1154##### Throws
1155​
1156If the updated data fails schema validation
1157​
1158##### Examples
1159​
1160```ts
1161// Update single item by key
1162const tx = collection.update("todo-1", (draft) => {
1163 draft.completed = true
1165await tx.isPersisted.promise
1166```
1167​
1168```ts
1169// Update multiple items
1170const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1171 drafts.forEach(draft => { draft.completed = true })
1173await tx.isPersisted.promise
1174```
1175​
1176```ts
1177// Update with metadata
1178const tx = collection.update("todo-1",
1179 { metadata: { reason: "user update" } },
1180 (draft) => { draft.text = "Updated text" }
1182await tx.isPersisted.promise
1183```
1184​
1185```ts
1186// Handle errors
1187try {
1188 const tx = collection.update("item-1", draft => { draft.value = "new" })
1189 await tx.isPersisted.promise
1190 console.log('Update successful')
1191} catch (error) {
1192 console.log('Update failed:', error)
1194```
1195​
1196##### Inherited from
1197​
1198[`CollectionImpl`](../../classes/collectionimpl.md).[`update`](../../classes/CollectionImpl.md#update)
1199​
1200#### Call Signature
1201​
1202```ts
1203update<TItem>(
1204 keys,
1205 config,
1206 callback): Transaction
1207```
1208​
1209Defined in: [packages/db/src/collection.ts:1731](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1731)
1210​
1211Updates one or more items in the collection using a callback function
1212​
1213##### Type Parameters
1214​
1215• **TItem** *extends* `object` = `T`
1216​
1217##### Parameters
1218​
1219###### keys
1220​
1221`unknown`[]
1222​
1223Single key or array of keys to update
1224​
1225###### config
1226​
1227[`OperationConfig`](../operationconfig.md)
1228​
1229###### callback
1230​
1231(`drafts`) => `void`
1232​
1233##### Returns
1234​
1235[`Transaction`](../../classes/transaction.md)
1236​
1237A Transaction object representing the update operation(s)
1238​
1239##### Throws
1240​
1241If the updated data fails schema validation
1242​
1243##### Examples
1244​
1245```ts
1246// Update single item by key
1247const tx = collection.update("todo-1", (draft) => {
1248 draft.completed = true
1250await tx.isPersisted.promise
1251```
1252​
1253```ts
1254// Update multiple items
1255const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1256 drafts.forEach(draft => { draft.completed = true })
1258await tx.isPersisted.promise
1259```
1260​
1261```ts
1262// Update with metadata
1263const tx = collection.update("todo-1",
1264 { metadata: { reason: "user update" } },
1265 (draft) => { draft.text = "Updated text" }
1267await tx.isPersisted.promise
1268```
1269​
1270```ts
1271// Handle errors
1272try {
1273 const tx = collection.update("item-1", draft => { draft.value = "new" })
1274 await tx.isPersisted.promise
1275 console.log('Update successful')
1276} catch (error) {
1277 console.log('Update failed:', error)
1279```
1280​
1281##### Inherited from
1282​
1283[`CollectionImpl`](../../classes/collectionimpl.md).[`update`](../../classes/CollectionImpl.md#update)
1284​
1285#### Call Signature
1286​
1287```ts
1288update<TItem>(id, callback): Transaction
1289```
1290​
1291Defined in: [packages/db/src/collection.ts:1738](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1738)
1292​
1293Updates one or more items in the collection using a callback function
1294​
1295##### Type Parameters
1296​
1297• **TItem** *extends* `object` = `T`
1298​
1299##### Parameters
1300​
1301###### id
1302​
1303`unknown`
1304​
1305###### callback
1306​
1307(`draft`) => `void`
1308​
1309##### Returns
1310​
1311[`Transaction`](../../classes/transaction.md)
1312​
1313A Transaction object representing the update operation(s)
1314​
1315##### Throws
1316​
1317If the updated data fails schema validation
1318​
1319##### Examples
1320​
1321```ts
1322// Update single item by key
1323const tx = collection.update("todo-1", (draft) => {
1324 draft.completed = true
1326await tx.isPersisted.promise
1327```
1328​
1329```ts
1330// Update multiple items
1331const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1332 drafts.forEach(draft => { draft.completed = true })
1334await tx.isPersisted.promise
1335```
1336​
1337```ts
1338// Update with metadata
1339const tx = collection.update("todo-1",
1340 { metadata: { reason: "user update" } },
1341 (draft) => { draft.text = "Updated text" }
1343await tx.isPersisted.promise
1344```
1345​
1346```ts
1347// Handle errors
1348try {
1349 const tx = collection.update("item-1", draft => { draft.value = "new" })
1350 await tx.isPersisted.promise
1351 console.log('Update successful')
1352} catch (error) {
1353 console.log('Update failed:', error)
1355```
1356​
1357##### Inherited from
1358​
1359[`CollectionImpl`](../../classes/collectionimpl.md).[`update`](../../classes/CollectionImpl.md#update)
1360​
1361#### Call Signature
1362​
1363```ts
1364update<TItem>(
1365 id,
1366 config,
1367 callback): Transaction
1368```
1369​
1370Defined in: [packages/db/src/collection.ts:1744](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1744)
1371​
1372Updates one or more items in the collection using a callback function
1373​
1374##### Type Parameters
1375​
1376• **TItem** *extends* `object` = `T`
1377​
1378##### Parameters
1379​
1380###### id
1381​
1382`unknown`
1383​
1384###### config
1385​
1386[`OperationConfig`](../operationconfig.md)
1387​
1388###### callback
1389​
1390(`draft`) => `void`
1391​
1392##### Returns
1393​
1394[`Transaction`](../../classes/transaction.md)
1395​
1396A Transaction object representing the update operation(s)
1397​
1398##### Throws
1399​
1400If the updated data fails schema validation
1401​
1402##### Examples
1403​
1404```ts
1405// Update single item by key
1406const tx = collection.update("todo-1", (draft) => {
1407 draft.completed = true
1409await tx.isPersisted.promise
1410```
1411​
1412```ts
1413// Update multiple items
1414const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1415 drafts.forEach(draft => { draft.completed = true })
1417await tx.isPersisted.promise
1418```
1419​
1420```ts
1421// Update with metadata
1422const tx = collection.update("todo-1",
1423 { metadata: { reason: "user update" } },
1424 (draft) => { draft.text = "Updated text" }
1426await tx.isPersisted.promise
1427```
1428​
1429```ts
1430// Handle errors
1431try {
1432 const tx = collection.update("item-1", draft => { draft.value = "new" })
1433 await tx.isPersisted.promise
1434 console.log('Update successful')
1435} catch (error) {
1436 console.log('Update failed:', error)
1438```
1439​
1440##### Inherited from
1441​
1442[`CollectionImpl`](../../classes/collectionimpl.md).[`update`](../../classes/CollectionImpl.md#update)
1443​
1444***
1445​
1446### values()
1447​
1448```ts
1449values(): IterableIterator<T>
1450```
1451​
1452Defined in: [packages/db/src/collection.ts:1022](https://github.com/TanStack/db/blob/main/packages/db/src/collection.ts#L1022)
1453​
1454Get all values (virtual derived state)
1455​
1456#### Returns
1457​
1458`IterableIterator`\<`T`\>
1459​
1460#### Inherited from
1461​
1462[`CollectionImpl`](../../classes/collectionimpl.md).[`values`](../../classes/CollectionImpl.md#values)