Open History to see the last commit
1---
2id: CollectionImpl
3title: CollectionImpl
4---
5
6# Class: CollectionImpl\<TOutput, TKey, TUtils, TSchema, TInput\>
7
8Defined in: [packages/db/src/collection/index.ts:272](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L272)
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:318](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L318)
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:289](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L289)
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:301](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L301)
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:290](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L290)
94
95***
96
97### config
98
99```ts
100config: CollectionConfig<TOutput, TKey, TSchema>;
101```
102
103Defined in: [packages/db/src/collection/index.ts:280](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L280)
104
105***
106
107### deferDataRefresh
108
109```ts
110deferDataRefresh: Promise<void> | null = null;
111```
112
113Defined in: [packages/db/src/collection/index.ts:308](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L308)
114
115When set, collection consumers should defer processing incoming data
116refreshes until this promise resolves. This prevents stale data from
117overwriting optimistic state while pending writes are being applied.
118
119***
120
121### id
122
123```ts
124id: string;
125```
126
127Defined in: [packages/db/src/collection/index.ts:279](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L279)
128
129***
130
131### utils
132
133```ts
134utils: Record<string, Fn> = {};
135```
136
137Defined in: [packages/db/src/collection/index.ts:284](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L284)
138
139## Accessors
140
141### compareOptions
142
143#### Get Signature
144
145```ts
146get compareOptions(): StringCollationConfig;
147```
148
149Defined in: [packages/db/src/collection/index.ts:643](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L643)
150
151##### Returns
152
153[`StringCollationConfig`](../type-aliases/StringCollationConfig.md)
154
155***
156
157### indexes
158
159#### Get Signature
160
161```ts
162get indexes(): Map<number, BaseIndex<TKey>>;
163```
164
165Defined in: [packages/db/src/collection/index.ts:628](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L628)
166
167Get resolved indexes for query optimization
168
169##### Returns
170
171`Map`\<`number`, [`BaseIndex`](BaseIndex.md)\<`TKey`\>\>
172
173***
174
175### isLoadingSubset
176
177#### Get Signature
178
179```ts
180get isLoadingSubset(): boolean;
181```
182
183Defined in: [packages/db/src/collection/index.ts:456](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L456)
184
185Check if the collection is currently loading more data
186
187##### Returns
188
189`boolean`
190
191true if the collection has pending load more operations, false otherwise
192
193***
194
195### size
196
197#### Get Signature
198
199```ts
200get size(): number;
201```
202
203Defined in: [packages/db/src/collection/index.ts:493](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L493)
204
205Get the current size of the collection (cached)
206
207##### Returns
208
209`number`
210
211***
212
213### state
214
215#### Get Signature
216
217```ts
218get state(): Map<TKey, WithVirtualProps<TOutput, TKey>>;
219```
220
221Defined in: [packages/db/src/collection/index.ts:820](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L820)
222
223Gets the current state of the collection as a Map
224
225##### Example
226
227```ts
228const itemsMap = collection.state
229console.log(`Collection has ${itemsMap.size} items`)
230
231for (const [key, item] of itemsMap) {
232 console.log(`${key}: ${item.title}`)
233}
234
235// Check if specific item exists
236if (itemsMap.has("todo-1")) {
237 console.log("Todo 1 exists:", itemsMap.get("todo-1"))
238}
239```
240
241##### Returns
242
243`Map`\<`TKey`, [`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>\>
244
245Map containing all items in the collection, with keys as identifiers
246
247***
248
249### status
250
251#### Get Signature
252
253```ts
254get status(): CollectionStatus;
255```
256
257Defined in: [packages/db/src/collection/index.ts:411](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L411)
258
259Gets the current status of the collection
260
261##### Returns
262
263[`CollectionStatus`](../type-aliases/CollectionStatus.md)
264
265***
266
267### subscriberCount
268
269#### Get Signature
270
271```ts
272get subscriberCount(): number;
273```
274
275Defined in: [packages/db/src/collection/index.ts:418](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L418)
276
277Get the number of subscribers to the collection
278
279##### Returns
280
281`number`
282
283***
284
285### toArray
286
287#### Get Signature
288
289```ts
290get toArray(): WithVirtualProps<TOutput, TKey>[];
291```
292
293Defined in: [packages/db/src/collection/index.ts:849](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L849)
294
295Gets the current state of the collection as an Array
296
297##### Returns
298
299[`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>[]
300
301An Array containing all items in the collection
302
303## Methods
304
305### \[iterator\]()
306
307```ts
308iterator: IterableIterator<[TKey, WithVirtualProps<TOutput, TKey>]>;
309```
310
311Defined in: [packages/db/src/collection/index.ts:531](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L531)
312
313Get all entries (virtual derived state)
314
315#### Returns
316
317`IterableIterator`\<\[`TKey`, [`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>\]\>
318
319***
320
321### cleanup()
322
323```ts
324cleanup(): Promise<void>;
325```
326
327Defined in: [packages/db/src/collection/index.ts:988](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L988)
328
329Clean up the collection by stopping sync and clearing data
330This can be called manually or automatically by garbage collection
331
332#### Returns
333
334`Promise`\<`void`\>
335
336***
337
338### createIndex()
339
340```ts
341createIndex<TIndexType>(indexCallback, config): BaseIndex<TKey>;
342```
343
344Defined in: [packages/db/src/collection/index.ts:597](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L597)
345
346Creates an index on a collection for faster queries.
347Indexes significantly improve query performance by allowing constant time lookups
348and logarithmic time range queries instead of full scans.
349
350#### Type Parameters
351
352##### TIndexType
353
354`TIndexType` *extends* [`IndexConstructor`](../type-aliases/IndexConstructor.md)\<`TKey`\>
355
356#### Parameters
357
358##### indexCallback
359
360(`row`) => `any`
361
362Function that extracts the indexed value from each item
363
364##### config
365
366[`IndexOptions`](../interfaces/IndexOptions.md)\<`TIndexType`\> = `{}`
367
368Configuration including index type and type-specific options
369
370#### Returns
371
372[`BaseIndex`](BaseIndex.md)\<`TKey`\>
373
374The created index
375
376#### Example
377
378```ts
379import { BasicIndex } from '@tanstack/db'
380
381// Create an index with explicit type
382const ageIndex = collection.createIndex((row) => row.age, {
383 indexType: BasicIndex
384})
385
386// Create an index with collection's default type
387const nameIndex = collection.createIndex((row) => row.name)
388```
389
390***
391
392### currentStateAsChanges()
393
394```ts
395currentStateAsChanges(options):
396 | void
397 | ChangeMessage<WithVirtualProps<TOutput, TKey>, string | number>[];
398```
399
400Defined in: [packages/db/src/collection/index.ts:887](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L887)
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)\<[`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>, `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:797](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L797)
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)
496}
497```
498
499***
500
501### entries()
502
503```ts
504entries(): IterableIterator<[TKey, WithVirtualProps<TOutput, TKey>]>;
505```
506
507Defined in: [packages/db/src/collection/index.ts:519](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L519)
508
509Get all entries (virtual derived state)
510
511#### Returns
512
513`IterableIterator`\<\[`TKey`, [`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>\]\>
514
515***
516
517### forEach()
518
519```ts
520forEach(callbackfn): void;
521```
522
523Defined in: [packages/db/src/collection/index.ts:540](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L540)
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):
543 | WithVirtualProps<TOutput, TKey>
544 | undefined;
545```
546
547Defined in: [packages/db/src/collection/index.ts:479](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L479)
548
549Get the current value for a key (virtual derived state)
550
551#### Parameters
552
553##### key
554
555`TKey`
556
557#### Returns
558
559 \| [`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>
560 \| `undefined`
561
562***
563
564### getIndexMetadata()
565
566```ts
567getIndexMetadata(): CollectionIndexMetadata[];
568```
569
570Defined in: [packages/db/src/collection/index.ts:621](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L621)
571
572Returns a snapshot of current index metadata sorted by indexId.
573Persistence wrappers can use this to bootstrap index state if indexes were
574created before event listeners were attached.
575
576#### Returns
577
578[`CollectionIndexMetadata`](../interfaces/CollectionIndexMetadata.md)[]
579
580***
581
582### getKeyFromItem()
583
584```ts
585getKeyFromItem(item): TKey;
586```
587
588Defined in: [packages/db/src/collection/index.ts:571](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L571)
589
590#### Parameters
591
592##### item
593
594`TOutput`
595
596#### Returns
597
598`TKey`
599
600***
601
602### has()
603
604```ts
605has(key): boolean;
606```
607
608Defined in: [packages/db/src/collection/index.ts:486](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L486)
609
610Check if a key exists in the collection (virtual derived state)
611
612#### Parameters
613
614##### key
615
616`TKey`
617
618#### Returns
619
620`boolean`
621
622***
623
624### insert()
625
626```ts
627insert(data, config?): Transaction<Record<string, unknown>>;
628```
629
630Defined in: [packages/db/src/collection/index.ts:684](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L684)
631
632Inserts one or more items into the collection
633
634#### Parameters
635
636##### data
637
638`TInput` | `TInput`[]
639
640##### config?
641
642[`InsertConfig`](../interfaces/InsertConfig.md)
643
644Optional configuration including metadata
645
646#### Returns
647
648[`Transaction`](../interfaces/Transaction.md)\<`Record`\<`string`, `unknown`\>\>
649
650A Transaction object representing the insert operation(s)
651
652#### Throws
653
654If the data fails schema validation
655
656#### Examples
657
658```ts
659// Insert a single todo (requires onInsert handler)
660const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
661await tx.isPersisted.promise
662```
663
664```ts
665// Insert multiple todos at once
666const tx = collection.insert([
667 { id: "1", text: "Buy milk", completed: false },
668 { id: "2", text: "Walk dog", completed: true }
669])
670await tx.isPersisted.promise
671```
672
673```ts
674// Insert with metadata
675const tx = collection.insert({ id: "1", text: "Buy groceries" },
676 { metadata: { source: "mobile-app" } }
677)
678await tx.isPersisted.promise
679```
680
681```ts
682// Handle errors
683try {
684 const tx = collection.insert({ id: "1", text: "New item" })
685 await tx.isPersisted.promise
686 console.log('Insert successful')
687} catch (error) {
688 console.log('Insert failed:', error)
689}
690```
691
692***
693
694### isReady()
695
696```ts
697isReady(): boolean;
698```
699
700Defined in: [packages/db/src/collection/index.ts:448](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L448)
701
702Check if the collection is ready for use
703Returns true if the collection has been marked as ready by its sync implementation
704
705#### Returns
706
707`boolean`
708
709true if the collection is ready, false otherwise
710
711#### Example
712
713```ts
714if (collection.isReady()) {
715 console.log('Collection is ready, data is available')
716 // Safe to access collection.state
717} else {
718 console.log('Collection is still loading')
719}
720```
721
722***
723
724### keys()
725
726```ts
727keys(): IterableIterator<TKey>;
728```
729
730Defined in: [packages/db/src/collection/index.ts:500](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L500)
731
732Get all keys (virtual derived state)
733
734#### Returns
735
736`IterableIterator`\<`TKey`\>
737
738***
739
740### map()
741
742```ts
743map<U>(callbackfn): U[];
744```
745
746Defined in: [packages/db/src/collection/index.ts:556](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L556)
747
748Create a new array with the results of calling a function for each entry in the collection
749
750#### Type Parameters
751
752##### U
753
754`U`
755
756#### Parameters
757
758##### callbackfn
759
760(`value`, `key`, `index`) => `U`
761
762#### Returns
763
764`U`[]
765
766***
767
768### off()
769
770```ts
771off<T>(event, callback): void;
772```
773
774Defined in: [packages/db/src/collection/index.ts:967](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L967)
775
776Unsubscribe from a collection event
777
778#### Type Parameters
779
780##### T
781
782`T` *extends*
783 \| `"status:error"`
784 \| `"status:idle"`
785 \| `"status:loading"`
786 \| `"status:ready"`
787 \| `"status:cleaned-up"`
788 \| `"status:change"`
789 \| `"subscribers:change"`
790 \| `"loadingSubset:change"`
791 \| `"truncate"`
792 \| `"index:added"`
793 \| `"index:removed"`
794
795#### Parameters
796
797##### event
798
799`T`
800
801##### callback
802
803`CollectionEventHandler`\<`T`\>
804
805#### Returns
806
807`void`
808
809***
810
811### on()
812
813```ts
814on<T>(event, callback): () => void;
815```
816
817Defined in: [packages/db/src/collection/index.ts:947](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L947)
818
819Subscribe to a collection event
820
821#### Type Parameters
822
823##### T
824
825`T` *extends*
826 \| `"status:error"`
827 \| `"status:idle"`
828 \| `"status:loading"`
829 \| `"status:ready"`
830 \| `"status:cleaned-up"`
831 \| `"status:change"`
832 \| `"subscribers:change"`
833 \| `"loadingSubset:change"`
834 \| `"truncate"`
835 \| `"index:added"`
836 \| `"index:removed"`
837
838#### Parameters
839
840##### event
841
842`T`
843
844##### callback
845
846`CollectionEventHandler`\<`T`\>
847
848#### Returns
849
850```ts
851(): void;
852```
853
854##### Returns
855
856`void`
857
858***
859
860### once()
861
862```ts
863once<T>(event, callback): () => void;
864```
865
866Defined in: [packages/db/src/collection/index.ts:957](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L957)
867
868Subscribe to a collection event once
869
870#### Type Parameters
871
872##### T
873
874`T` *extends*
875 \| `"status:error"`
876 \| `"status:idle"`
877 \| `"status:loading"`
878 \| `"status:ready"`
879 \| `"status:cleaned-up"`
880 \| `"status:change"`
881 \| `"subscribers:change"`
882 \| `"loadingSubset:change"`
883 \| `"truncate"`
884 \| `"index:added"`
885 \| `"index:removed"`
886
887#### Parameters
888
889##### event
890
891`T`
892
893##### callback
894
895`CollectionEventHandler`\<`T`\>
896
897#### Returns
898
899```ts
900(): void;
901```
902
903##### Returns
904
905`void`
906
907***
908
909### onFirstReady()
910
911```ts
912onFirstReady(callback): void;
913```
914
915Defined in: [packages/db/src/collection/index.ts:432](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L432)
916
917Register a callback to be executed when the collection first becomes ready
918Useful for preloading collections
919
920#### Parameters
921
922##### callback
923
924() => `void`
925
926Function to call when the collection first becomes ready
927
928#### Returns
929
930`void`
931
932#### Example
933
934```ts
935collection.onFirstReady(() => {
936 console.log('Collection is ready for the first time')
937 // Safe to access collection.state now
938})
939```
940
941***
942
943### preload()
944
945```ts
946preload(): Promise<void>;
947```
948
949Defined in: [packages/db/src/collection/index.ts:472](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L472)
950
951Preload the collection data by starting sync if not already started
952Multiple concurrent calls will share the same promise
953
954#### Returns
955
956`Promise`\<`void`\>
957
958***
959
960### removeIndex()
961
962```ts
963removeIndex(indexOrId): boolean;
964```
965
966Defined in: [packages/db/src/collection/index.ts:612](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L612)
967
968Removes an index created with createIndex.
969Returns true when an index existed and was removed.
970
971Best-effort semantics: removing an index guarantees it is detached from
972collection query planning. Existing index proxy references should be treated
973as invalid after removal.
974
975#### Parameters
976
977##### indexOrId
978
979`number` | [`BaseIndex`](BaseIndex.md)\<`TKey`\>
980
981#### Returns
982
983`boolean`
984
985***
986
987### startSyncImmediate()
988
989```ts
990startSyncImmediate(): void;
991```
992
993Defined in: [packages/db/src/collection/index.ts:464](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L464)
994
995Start sync immediately - internal method for compiled queries
996This bypasses lazy loading for special cases like live query results
997
998#### Returns
999
1000`void`
1001
1002***
1003
1004### stateWhenReady()
1005
1006```ts
1007stateWhenReady(): Promise<Map<TKey, WithVirtualProps<TOutput, TKey>>>;
1008```
1009
1010Defined in: [packages/db/src/collection/index.ts:834](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L834)
1011
1012Gets the current state of the collection as a Map, but only resolves when data is available
1013Waits for the first sync commit to complete before resolving
1014
1015#### Returns
1016
1017`Promise`\<`Map`\<`TKey`, [`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>\>\>
1018
1019Promise that resolves to a Map containing all items in the collection
1020
1021***
1022
1023### subscribeChanges()
1024
1025```ts
1026subscribeChanges(callback, options): CollectionSubscription;
1027```
1028
1029Defined in: [packages/db/src/collection/index.ts:935](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L935)
1030
1031Subscribe to changes in the collection
1032
1033#### Parameters
1034
1035##### callback
1036
1037(`changes`) => `void`
1038
1039Function called when items change
1040
1041##### options
1042
1043[`SubscribeChangesOptions`](../interfaces/SubscribeChangesOptions.md)\<`TOutput`, `TKey`\> = `{}`
1044
1045Subscription options including includeInitialState and where filter
1046
1047#### Returns
1048
1049`CollectionSubscription`
1050
1051Unsubscribe function - Call this to stop listening for changes
1052
1053#### Examples
1054
1055```ts
1056// Basic subscription
1057const subscription = collection.subscribeChanges((changes) => {
1058 changes.forEach(change => {
1059 console.log(`${change.type}: ${change.key}`, change.value)
1060 })
1061})
1062
1063// Later: subscription.unsubscribe()
1064```
1065
1066```ts
1067// Include current state immediately
1068const subscription = collection.subscribeChanges((changes) => {
1069 updateUI(changes)
1070}, { includeInitialState: true })
1071```
1072
1073```ts
1074// Subscribe only to changes matching a condition using where callback
1075import { eq } from "@tanstack/db"
1076
1077const subscription = collection.subscribeChanges((changes) => {
1078 updateUI(changes)
1079}, {
1080 includeInitialState: true,
1081 where: (row) => eq(row.status, "active")
1082})
1083```
1084
1085```ts
1086// Using multiple conditions with and()
1087import { and, eq, gt } from "@tanstack/db"
1088
1089const subscription = collection.subscribeChanges((changes) => {
1090 updateUI(changes)
1091}, {
1092 where: (row) => and(eq(row.status, "active"), gt(row.priority, 5))
1093})
1094```
1095
1096***
1097
1098### toArrayWhenReady()
1099
1100```ts
1101toArrayWhenReady(): Promise<WithVirtualProps<TOutput, TKey>[]>;
1102```
1103
1104Defined in: [packages/db/src/collection/index.ts:859](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L859)
1105
1106Gets the current state of the collection as an Array, but only resolves when data is available
1107Waits for the first sync commit to complete before resolving
1108
1109#### Returns
1110
1111`Promise`\<[`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>[]\>
1112
1113Promise that resolves to an Array containing all items in the collection
1114
1115***
1116
1117### update()
1118
1119#### Call Signature
1120
1121```ts
1122update(key, callback): Transaction;
1123```
1124
1125Defined in: [packages/db/src/collection/index.ts:729](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L729)
1126
1127Updates one or more items in the collection using a callback function
1128
1129##### Parameters
1130
1131###### key
1132
1133`unknown`[]
1134
1135###### callback
1136
1137(`drafts`) => `void`
1138
1139##### Returns
1140
1141[`Transaction`](../interfaces/Transaction.md)
1142
1143A Transaction object representing the update operation(s)
1144
1145##### Throws
1146
1147If the updated data fails schema validation
1148
1149##### Examples
1150
1151```ts
1152// Update single item by key
1153const tx = collection.update("todo-1", (draft) => {
1154 draft.completed = true
1155})
1156await tx.isPersisted.promise
1157```
1158
1159```ts
1160// Update multiple items
1161const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1162 drafts.forEach(draft => { draft.completed = true })
1163})
1164await tx.isPersisted.promise
1165```
1166
1167```ts
1168// Update with metadata
1169const tx = collection.update("todo-1",
1170 { metadata: { reason: "user update" } },
1171 (draft) => { draft.text = "Updated text" }
1172)
1173await tx.isPersisted.promise
1174```
1175
1176```ts
1177// Handle errors
1178try {
1179 const tx = collection.update("item-1", draft => { draft.value = "new" })
1180 await tx.isPersisted.promise
1181 console.log('Update successful')
1182} catch (error) {
1183 console.log('Update failed:', error)
1184}
1185```
1186
1187#### Call Signature
1188
1189```ts
1190update(
1191 keys,
1192 config,
1193 callback): Transaction;
1194```
1195
1196Defined in: [packages/db/src/collection/index.ts:735](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L735)
1197
1198Updates one or more items in the collection using a callback function
1199
1200##### Parameters
1201
1202###### keys
1203
1204`unknown`[]
1205
1206Single key or array of keys to update
1207
1208###### config
1209
1210[`OperationConfig`](../interfaces/OperationConfig.md)
1211
1212###### callback
1213
1214(`drafts`) => `void`
1215
1216##### Returns
1217
1218[`Transaction`](../interfaces/Transaction.md)
1219
1220A Transaction object representing the update operation(s)
1221
1222##### Throws
1223
1224If the updated data fails schema validation
1225
1226##### Examples
1227
1228```ts
1229// Update single item by key
1230const tx = collection.update("todo-1", (draft) => {
1231 draft.completed = true
1232})
1233await tx.isPersisted.promise
1234```
1235
1236```ts
1237// Update multiple items
1238const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1239 drafts.forEach(draft => { draft.completed = true })
1240})
1241await tx.isPersisted.promise
1242```
1243
1244```ts
1245// Update with metadata
1246const tx = collection.update("todo-1",
1247 { metadata: { reason: "user update" } },
1248 (draft) => { draft.text = "Updated text" }
1249)
1250await tx.isPersisted.promise
1251```
1252
1253```ts
1254// Handle errors
1255try {
1256 const tx = collection.update("item-1", draft => { draft.value = "new" })
1257 await tx.isPersisted.promise
1258 console.log('Update successful')
1259} catch (error) {
1260 console.log('Update failed:', error)
1261}
1262```
1263
1264#### Call Signature
1265
1266```ts
1267update(id, callback): Transaction;
1268```
1269
1270Defined in: [packages/db/src/collection/index.ts:742](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L742)
1271
1272Updates one or more items in the collection using a callback function
1273
1274##### Parameters
1275
1276###### id
1277
1278`unknown`
1279
1280###### callback
1281
1282(`draft`) => `void`
1283
1284##### Returns
1285
1286[`Transaction`](../interfaces/Transaction.md)
1287
1288A Transaction object representing the update operation(s)
1289
1290##### Throws
1291
1292If the updated data fails schema validation
1293
1294##### Examples
1295
1296```ts
1297// Update single item by key
1298const tx = collection.update("todo-1", (draft) => {
1299 draft.completed = true
1300})
1301await tx.isPersisted.promise
1302```
1303
1304```ts
1305// Update multiple items
1306const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1307 drafts.forEach(draft => { draft.completed = true })
1308})
1309await tx.isPersisted.promise
1310```
1311
1312```ts
1313// Update with metadata
1314const tx = collection.update("todo-1",
1315 { metadata: { reason: "user update" } },
1316 (draft) => { draft.text = "Updated text" }
1317)
1318await tx.isPersisted.promise
1319```
1320
1321```ts
1322// Handle errors
1323try {
1324 const tx = collection.update("item-1", draft => { draft.value = "new" })
1325 await tx.isPersisted.promise
1326 console.log('Update successful')
1327} catch (error) {
1328 console.log('Update failed:', error)
1329}
1330```
1331
1332#### Call Signature
1333
1334```ts
1335update(
1336 id,
1337 config,
1338 callback): Transaction;
1339```
1340
1341Defined in: [packages/db/src/collection/index.ts:748](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L748)
1342
1343Updates one or more items in the collection using a callback function
1344
1345##### Parameters
1346
1347###### id
1348
1349`unknown`
1350
1351###### config
1352
1353[`OperationConfig`](../interfaces/OperationConfig.md)
1354
1355###### callback
1356
1357(`draft`) => `void`
1358
1359##### Returns
1360
1361[`Transaction`](../interfaces/Transaction.md)
1362
1363A Transaction object representing the update operation(s)
1364
1365##### Throws
1366
1367If the updated data fails schema validation
1368
1369##### Examples
1370
1371```ts
1372// Update single item by key
1373const tx = collection.update("todo-1", (draft) => {
1374 draft.completed = true
1375})
1376await tx.isPersisted.promise
1377```
1378
1379```ts
1380// Update multiple items
1381const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
1382 drafts.forEach(draft => { draft.completed = true })
1383})
1384await tx.isPersisted.promise
1385```
1386
1387```ts
1388// Update with metadata
1389const tx = collection.update("todo-1",
1390 { metadata: { reason: "user update" } },
1391 (draft) => { draft.text = "Updated text" }
1392)
1393await tx.isPersisted.promise
1394```
1395
1396```ts
1397// Handle errors
1398try {
1399 const tx = collection.update("item-1", draft => { draft.value = "new" })
1400 await tx.isPersisted.promise
1401 console.log('Update successful')
1402} catch (error) {
1403 console.log('Update failed:', error)
1404}
1405```
1406
1407***
1408
1409### validateData()
1410
1411```ts
1412validateData(
1413 data,
1414 type,
1415 key?): TOutput;
1416```
1417
1418Defined in: [packages/db/src/collection/index.ts:635](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L635)
1419
1420Validates the data against the schema
1421
1422#### Parameters
1423
1424##### data
1425
1426`unknown`
1427
1428##### type
1429
1430`"insert"` | `"update"`
1431
1432##### key?
1433
1434`TKey`
1435
1436#### Returns
1437
1438`TOutput`
1439
1440***
1441
1442### values()
1443
1444```ts
1445values(): IterableIterator<WithVirtualProps<TOutput, TKey>>;
1446```
1447
1448Defined in: [packages/db/src/collection/index.ts:507](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L507)
1449
1450Get all values (virtual derived state)
1451
1452#### Returns
1453
1454`IterableIterator`\<[`WithVirtualProps`](../type-aliases/WithVirtualProps.md)\<`TOutput`, `TKey`\>\>
1455
1456***
1457
1458### waitFor()
1459
1460```ts
1461waitFor<T>(event, timeout?): Promise<AllCollectionEvents[T]>;
1462```
1463
1464Defined in: [packages/db/src/collection/index.ts:977](https://github.com/TanStack/db/blob/main/packages/db/src/collection/index.ts#L977)
1465
1466Wait for a collection event
1467
1468#### Type Parameters
1469
1470##### T
1471
1472`T` *extends*
1473 \| `"status:error"`
1474 \| `"status:idle"`
1475 \| `"status:loading"`
1476 \| `"status:ready"`
1477 \| `"status:cleaned-up"`
1478 \| `"status:change"`
1479 \| `"subscribers:change"`
1480 \| `"loadingSubset:change"`
1481 \| `"truncate"`
1482 \| `"index:added"`
1483 \| `"index:removed"`
1484
1485#### Parameters
1486
1487##### event
1488
1489`T`
1490
1491##### timeout?
1492
1493`number`
1494
1495#### Returns
1496
1497`Promise`\<`AllCollectionEvents`\[`T`\]\>