From 13e69b0faa5a8b4905e2cde5fd3a754d40f722be Mon Sep 17 00:00:00 2001 From: nrahnema Date: Tue, 16 Dec 2025 02:31:38 -0500 Subject: [PATCH] fix(query-core): fix queriesObserver result and observer length mismatch In 1b54538, `setOptions` was changed to call `notifyListeners` which eventually leads to `QueriesObserver.setQueries` 1. Updating `#observerMatches` 2. Calling `setOptions` which leads to `#notify` being called 3. Updating `#result` This is an issue when `#notify` is called before the `#result` is updated, as `#trackResult` assumes these two are the same length, which may not be the case if the number of queries changed. When the length increases, `observerResult` becomes `undefined` and the function throws an exception. Fix by moving the `#observerMatches` assignment later in the function, next to the `#observers` and `#result` assignment. --- .changeset/orange-flowers-post.md | 5 +++++ packages/query-core/src/queriesObserver.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 .changeset/orange-flowers-post.md diff --git a/.changeset/orange-flowers-post.md b/.changeset/orange-flowers-post.md new file mode 100644 index 0000000000..636873d999 --- /dev/null +++ b/.changeset/orange-flowers-post.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': patch +--- + +fix useQueries race condition on queries length change (#9971) diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index 0590e1e995..a8ad40a029 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -106,7 +106,6 @@ export class QueriesObserver< const prevObservers = this.#observers const newObserverMatches = this.#findMatchingObservers(this.#queries) - this.#observerMatches = newObserverMatches // set options for the new observers to notify of changes newObserverMatches.forEach((match) => @@ -134,6 +133,7 @@ export class QueriesObserver< if (!hasStructuralChange && !hasResultChange) return if (hasStructuralChange) { + this.#observerMatches = newObserverMatches this.#observers = newObservers }