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