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

CollectionImpl.md

1,441 lines26.5 KB

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