Skip to content

usePacedMutations with writeUpdate causes rollback on every other update #904

@em2724

Description

@em2724
"@tanstack/query-db-collection": "1.0.4",
"@tanstack/react-db": "0.1.49",

Description
When using usePacedMutations with writeUpdate, there's a consistent bug where every other update rolls back to the previous state when the mutation resolves.

Current Behavior

  • 1st update → Works correctly
  • 2nd update → Optimistic update applies, API call succeeds, but when writeUpdate is called, rolls back to 1st update's data
  • 3rd update → Works correctly
  • 4th update → Optimistic update applies, API call succeeds, but rolls back to 3rd update's data
  • Continues alternating
const mutateAnnotation = usePacedMutations<{
    type: 'insert' | 'update' | 'delete';
    id: string;
    data?: Partial<Annotation>;
  }>({
    onMutate: ({ type, id, data }) => {
      if (type === 'update') {
        // This works correctly - optimistic update applies
        annotationsCollection.update(id, draft => {
          draft.coords = data.coords;
        });
      }
    },
    mutationFn: async ({ transaction }) => {
      const mutation = transaction.mutations[0];
      
      if (mutation.type === 'update') {
        const id = mutation.original.id;
        
        // Server update succeeds
        await api.put(`/annotation/${id}`, mutation.changes);
        
        // BUG: On every other update, this causes rollback to previous state
        annotationsCollection.utils.writeUpdate({ 
          id, 
          ...mutation.changes 
        });
      }
    },
    strategy: queueStrategy({
      wait: 0, // Bug occurs with any wait value
      addItemsTo: 'back',
      getItemsFrom: 'front'
    })
  });

Important: The backend API calls complete successfully with correct data. NOT a race condition - happens even when waiting for each update to fully complete before triggering the next.

Update
Just noticed that this bug was reported by someone else a few hours before me here: #902

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions