Skip to content

Queries on date has a mutating impact on other queries #616

@fuegoio

Description

@fuegoio

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!

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