Skip to content

Sums are updated twice in live queries #609

@fuegoio

Description

@fuegoio

Hello 👋

I'm using Tanstack DB with a custom collection I created based on tRPC. I use a sum in a live query and I noticed that if I have an action on delete (implementing an onDelete basically), the sum amount is updated twice.

Here is a CodeSandbox that reproduces the issue: https://codesandbox.io/p/sandbox/dark-worker-8y8342

Basically, when the optimistic update is triggered, the sum is correctly updated. But if there is a possible rollback, ie on onDelete or onUpdate is implemented, when the optimistic update should be discarded it is not and the sum amount is updated again.

Minimal repro code here:

import {
  useLiveQuery,
  sum,
  localOnlyCollectionOptions,
  createCollection,
} from "@tanstack/react-db";

export const numbersCollection = createCollection(
  localOnlyCollectionOptions({
    id: "numbers",
    getKey: (item) => item.id,
    initialData: [
      { id: 0, number: 15 },
      { id: 1, number: 15 },
      { id: 2, number: 15 },
    ],
    onDelete: async ({ transaction }) => {
      const { original, modified } = transaction.mutations[0];
      return modified;
    },
  })
);

export default function App() {
  const query = useLiveQuery((q) =>
    q.from({ numbers: numbersCollection }).select(({ numbers }) => ({
      totalNumber: sum(numbers.number),
    }))
  );

  const deleteItem = () => {
    numbersCollection.delete(0);
  };

  return (
    <div className="App">
      <h1>Total: {query.data.at(0).totalNumber}</h1>
      <button onClick={deleteItem}>Delete item</button>
    </div>
  );
}

The sum is first 45, but when clicking on the button it goes first to 30 after the optimistic update, and then 15.

Thanks a lot your for time and work!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions