diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index 37557a6e72..a15139d24e 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -207,59 +207,43 @@ export class QueriesObserver< #findMatchingObservers( queries: Array, ): Array { - const prevObservers = this.#observers const prevObserversMap = new Map( - prevObservers.map((observer) => [observer.options.queryHash, observer]), + this.#observers.map((observer) => [observer.options.queryHash, observer]), ) - const defaultedQueryOptions = queries.map((options) => - this.#client.defaultQueryOptions(options), - ) - - const matchingObservers: Array = - defaultedQueryOptions.flatMap((defaultedOptions) => { - const match = prevObserversMap.get(defaultedOptions.queryHash) - if (match != null) { - return [{ defaultedQueryOptions: defaultedOptions, observer: match }] - } - return [] - }) - - const matchedQueryHashes = new Set( - matchingObservers.map((match) => match.defaultedQueryOptions.queryHash), - ) - const unmatchedQueries = defaultedQueryOptions.filter( - (defaultedOptions) => !matchedQueryHashes.has(defaultedOptions.queryHash), - ) + const observers: Array = [] - const getObserver = (options: QueryObserverOptions): QueryObserver => { + queries.forEach((options) => { const defaultedOptions = this.#client.defaultQueryOptions(options) - const currentObserver = this.#observers.find( - (o) => o.options.queryHash === defaultedOptions.queryHash, - ) + const match = prevObserversMap.get(defaultedOptions.queryHash) + if (match) { + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer: match, + }) + } else { + const existingObserver = this.#observers.find( + (o) => o.options.queryHash === defaultedOptions.queryHash, + ) + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer: + existingObserver ?? + new QueryObserver(this.#client, defaultedOptions), + }) + } + }) + + return observers.sort((a, b) => { return ( - currentObserver ?? new QueryObserver(this.#client, defaultedOptions) + queries.findIndex( + (q) => q.queryHash === a.defaultedQueryOptions.queryHash, + ) - + queries.findIndex( + (q) => q.queryHash === b.defaultedQueryOptions.queryHash, + ) ) - } - - const newOrReusedObservers: Array = - unmatchedQueries.map((options) => { - return { - defaultedQueryOptions: options, - observer: getObserver(options), - } - }) - - const sortMatchesByOrderOfQueries = ( - a: QueryObserverMatch, - b: QueryObserverMatch, - ): number => - defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - - defaultedQueryOptions.indexOf(b.defaultedQueryOptions) - - return matchingObservers - .concat(newOrReusedObservers) - .sort(sortMatchesByOrderOfQueries) + }) } #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {