MCPcopy Create free account
hub / github.com/TanStack/db / writeBatch

Function writeBatch

packages/query-db-collection/src/manual-sync.ts:314–360  ·  view source on GitHub ↗
(callback: () => void)

Source from the content-addressed store, hash-verified

312 },
313
314 writeBatch(callback: () => void) {
315 const ctx = ensureContext()
316
317 // Check if we're already in a batch (nested batch)
318 const existingBatch = activeBatchContexts.get(ctx)
319 if (existingBatch?.isActive) {
320 throw new Error(
321 `Cannot nest writeBatch calls. Complete the current batch before starting a new one.`,
322 )
323 }
324
325 // Set up the batch context for this specific collection
326 const batchContext = {
327 operations: [] as Array<SyncOperation<TRow, TKey, TInsertInput>>,
328 isActive: true,
329 }
330 activeBatchContexts.set(ctx, batchContext)
331
332 try {
333 // Execute the callback - any write operations will be collected
334 const result = callback()
335
336 // Check if callback returns a promise (async function)
337 if (
338 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
339 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
340 result &&
341 typeof result === `object` &&
342 `then` in result &&
343 // @ts-expect-error - Runtime check for async callback, callback is typed as () => void but user might pass async
344 typeof result.then === `function`
345 ) {
346 throw new Error(
347 `writeBatch does not support async callbacks. The callback must be synchronous.`,
348 )
349 }
350
351 // Perform all collected operations
352 if (batchContext.operations.length > 0) {
353 performWriteOperations(batchContext.operations, ctx)
354 }
355 } finally {
356 // Always clear the batch context
357 batchContext.isActive = false
358 activeBatchContexts.delete(ctx)
359 }
360 },
361 }
362}

Callers

nothing calls this directly

Calls 5

ensureContextFunction · 0.85
performWriteOperationsFunction · 0.85
getMethod · 0.45
setMethod · 0.45
deleteMethod · 0.45

Tested by

no test coverage detected