TanStack / TanStack/db

Queries on date has a mutating impact on other queries

Open
#616 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
3.9k
Forks
266
Avg merge
1d 4h
Merged PRs (30d)
55

Description

Hello again 👋

I have a bug where I use an orderBy and a limit to get most recent items by a date. But weirdingly, when there is another query before this one that just filters on this date, the result is different and wrong.

Codesandbox that reproduces the issue: https://codesandbox.io/p/devbox/quirky-rui-mh7ypn

Minimal reproduction code:

export const numbersCollection = createCollection(
  localOnlyCollectionOptions({
    id: "dates",
    getKey: (item) => item.id,
    initialData: [
      {
        id: "1",
        date: new Date("2025-09-15"),
      },
      {
        id: "2",
        date: new Date("2025-09-10"),
      },
    ],
  })
);

export default function App() {
  const today = new Date();
  // Comment this query and the result will be different
  const firstQueryThatPoisonTheRest = useLiveQuery((q) => {
    return q
      .from({ numbers: numbersCollection })
      .where(({ numbers }) =>
        and(gt(numbers.date, today), lt(numbers.date, today))
      );
  });

  const query = useLiveQuery((q) =>
    q
      .from({ numbers: numbersCollection })
      .orderBy(({ numbers }) => numbers.date, "desc")
      .limit(1)
  );

  return (
    <div className="App">
      <h1>Id: {query.data.at(0).id}</h1>
    </div>
  );
}

When the firstQueryThatPoisonTheRest is commented, the result is Id: 1 which is what we want ("2025-09-15" > "2025-09-10"). But when this query runs first, the result is Id: 2, which is wrong.

Happy to help on this if needed, and thanks again for your work!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked CodeSandbox and the minimal TypeScript/TSX reproduction, then trace useLiveQuery's query execution and date comparison and orderBy handling. Done means the two-query case returns Id: 1 as the single result, without changing the existing ordering behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.