Skip to content
Source
Sign inSign up
TanStack/db

Add awaitPersisted() method to wait for record sync #661

Send to my agent
OpenKyleAMathews(GitHub profile, opens in a new tab) opened this issue 1 comment

Feature Request

Add a collection.awaitPersisted(id) method that returns a promise resolving when all active mutations for a given record have been persisted.

Motivation

Currently, to wait for a record to sync, you need to manually track the transaction:

const tx = collection.update(todoId, draft => { draft.completed = true })
await tx.isPersisted.promise

This requires holding onto the transaction reference. For fire-and-forget mutations or when multiple components might update the same record, it would be cleaner to await persistence by record ID:

collection.update(todoId, draft => { draft.completed = true })
// Later, anywhere in the app...
await collection.awaitPersisted(todoId)

Proposed API

collection.awaitPersisted(id: TKey): Promise<void>

Behavior:

  • Finds all active transactions affecting the given key
  • Waits for them to complete via Promise.all()
  • Rechecks for new mutations after completion (new txs might have started while waiting)
  • Loops until no active mutations remain
  • Resolves immediately if no active mutations exist for that key

Implementation

async awaitPersisted(key: TKey): Promise<void> {
  while (true) {
    const info = this.getOptimisticInfo(key)
    if (!info?.isOptimistic) return
    
    await Promise.all(info.mutations.map(m => m.transaction.isPersisted.promise))
    // Recheck - new mutations might have arrived while waiting
  }
}

The loop is necessary because new mutations can be added while waiting for current ones to complete.

Use Cases

  1. Navigation after save: Wait for sync before navigating away
  2. Sequential operations: Ensure first update completes before starting dependent operation
  3. Loading states: Show spinner until all pending changes for a record are persisted
  4. Testing: Easier to wait for specific records to sync in tests

Example Usage

// Simple case
await collection.awaitPersisted(todoId)

// Navigation
async function handleSaveAndClose() {
  collection.update(todoId, draft => { draft.text = newText })
  await collection.awaitPersisted(todoId)
  navigate('/todos')
}

// Testing
test('updates are persisted', async () => {
  collection.update('todo-1', draft => { draft.completed = true })
  await collection.awaitPersisted('todo-1')
  expect(mockApi.updateTodo).toHaveBeenCalled()
})

Implementation Notes

Builds on the existing getOptimisticInfo() infrastructure from #660 which already scans active transactions for a given key.

  1. +1 — hit this exact pain point in production.

    We're using queryCollectionOptions with onInsert for optimistic inserts where the server assigns the primary key. The current flow requires holding onto the transaction:

    const tx = notesCollection.insert({
      id: crypto.randomUUID(), // temp key
      text: content,
    })
    await tx.isPersisted.promise

    awaitPersisted(id) would simplify this significantly, especially for fire-and-forget patterns.

    Related footgun worth mentioning: isPersisted is a Deferred<T>, not a Promise<T>. Since Deferred has no .then() method, writing await tx.isPersisted (without .promise) silently resolves immediately — it doesn't wait for anything. TypeScript can't catch it because await accepts any. We're planning a docs PR to add a warning about this.

    awaitPersisted() would also eliminate this footgun entirely by returning a real Promise<void>.

Sign in to join this conversation.