MCPcopy Index your code
hub / github.com/TanStack/db / update

Method update

packages/db/src/collection/mutations.ts:267–459  ·  view source on GitHub ↗

* Updates one or more items in the collection using a callback function

(
    keys: (TKey | unknown) | Array<TKey | unknown>,
    configOrCallback:
      | ((draft: WritableDeep<TInput>) => void)
      | ((drafts: Array<WritableDeep<TInput>>) => void)
      | OperationConfig,
    maybeCallback?:
      | ((draft: WritableDeep<TInput>) => void)
      | ((drafts: Array<WritableDeep<TInput>>) => void),
  )

Source from the content-addressed store, hash-verified

265 * Updates one or more items in the collection using a callback function
266 */
267 update(
268 keys: (TKey | unknown) | Array<TKey | unknown>,
269 configOrCallback:
270 | ((draft: WritableDeep<TInput>) => void)
271 | ((drafts: Array<WritableDeep<TInput>>) => void)
272 | OperationConfig,
273 maybeCallback?:
274 | ((draft: WritableDeep<TInput>) => void)
275 | ((drafts: Array<WritableDeep<TInput>>) => void),
276 ) {
277 if (typeof keys === `undefined`) {
278 throw new MissingUpdateArgumentError()
279 }
280
281 const state = this.state
282 this.lifecycle.validateCollectionUsable(`update`)
283
284 const ambientTransaction = getActiveTransaction()
285
286 // If no ambient transaction exists, check for an onUpdate handler early
287 if (!ambientTransaction && !this.config.onUpdate) {
288 throw new MissingUpdateHandlerError()
289 }
290
291 const isArray = Array.isArray(keys)
292 const keysArray = isArray ? keys : [keys]
293
294 if (isArray && keysArray.length === 0) {
295 throw new NoKeysPassedToUpdateError()
296 }
297
298 const callback =
299 typeof configOrCallback === `function` ? configOrCallback : maybeCallback!
300 const config =
301 typeof configOrCallback === `function` ? {} : configOrCallback
302
303 // Get the current objects or empty objects if they don't exist
304 const currentObjects = keysArray.map((key) => {
305 const item = this.state.get(key)
306 if (!item) {
307 throw new UpdateKeyNotFoundError(key)
308 }
309
310 return item
311 }) as unknown as Array<TInput>
312
313 let changesArray
314 if (isArray) {
315 // Use the proxy to track changes for all objects
316 changesArray = withArrayChangeTracking(
317 currentObjects,
318 callback as (draft: Array<TInput>) => void,
319 )
320 } else {
321 const result = withChangeTracking(
322 currentObjects[0]!,
323 callback as (draft: TInput) => void,
324 )

Callers

nothing calls this directly

Calls 15

validateDataMethod · 0.95
generateGlobalKeyMethod · 0.95
getActiveTransactionFunction · 0.90
withArrayChangeTrackingFunction · 0.90
withChangeTrackingFunction · 0.90
safeRandomUUIDFunction · 0.90
createTransactionFunction · 0.90
filterMethod · 0.80
applyMutationsMethod · 0.80

Tested by

no test coverage detected