* Replaces the set of queries being observed. Existing `QueryObserver`s * are reused for queries that match an already-observed query hash; * observers for queries that are no longer present are destroyed, and new * observers are created and subscribed to for newly added queries. * *
(
queries: Array<QueryObserverOptions>,
options?: QueriesObserverOptions<TCombinedResult>,
)
| 125 | * ``` |
| 126 | */ |
| 127 | setQueries( |
| 128 | queries: Array<QueryObserverOptions>, |
| 129 | options?: QueriesObserverOptions<TCombinedResult>, |
| 130 | ): void { |
| 131 | this.#queries = queries |
| 132 | this.#options = options |
| 133 | |
| 134 | if (process.env.NODE_ENV !== 'production') { |
| 135 | const queryHashes = queries.map( |
| 136 | (query) => this.#client.defaultQueryOptions(query).queryHash, |
| 137 | ) |
| 138 | if (new Set(queryHashes).size !== queryHashes.length) { |
| 139 | console.warn( |
| 140 | '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.', |
| 141 | ) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | notifyManager.batch(() => { |
| 146 | const prevObservers = this.#observers |
| 147 | |
| 148 | const newObserverMatches = this.#findMatchingObservers(this.#queries) |
| 149 | |
| 150 | // set options for the new observers to notify of changes |
| 151 | newObserverMatches.forEach((match) => |
| 152 | match.observer.setOptions(match.defaultedQueryOptions), |
| 153 | ) |
| 154 | |
| 155 | const newObservers = newObserverMatches.map((match) => match.observer) |
| 156 | const newResult = newObservers.map((observer) => |
| 157 | observer.getCurrentResult(), |
| 158 | ) |
| 159 | |
| 160 | const hasLengthChange = prevObservers.length !== newObservers.length |
| 161 | const hasIndexChange = newObservers.some( |
| 162 | (observer, index) => observer !== prevObservers[index], |
| 163 | ) |
| 164 | const hasStructuralChange = hasLengthChange || hasIndexChange |
| 165 | |
| 166 | const hasResultChange = hasStructuralChange |
| 167 | ? true |
| 168 | : newResult.some((result, index) => { |
| 169 | const prev = this.#result[index] |
| 170 | return !prev || !shallowEqualObjects(result, prev) |
| 171 | }) |
| 172 | |
| 173 | if (!hasStructuralChange && !hasResultChange) return |
| 174 | |
| 175 | if (hasStructuralChange) { |
| 176 | this.#observerMatches = newObserverMatches |
| 177 | this.#observers = newObservers |
| 178 | } |
| 179 | |
| 180 | this.#result = newResult |
| 181 | |
| 182 | if (!this.hasListeners()) return |
| 183 | |
| 184 | if (hasStructuralChange) { |
no test coverage detected