* 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. * @para
(
queries: Array<QueryObserverOptions>,
options?: QueriesObserverOptions<TCombinedResult>,
)
| 134 | * ``` |
| 135 | */ |
| 136 | setQueries( |
| 137 | queries: Array<QueryObserverOptions>, |
| 138 | options?: QueriesObserverOptions<TCombinedResult>, |
| 139 | ): void { |
| 140 | this.#queries = queries |
| 141 | this.#options = options |
| 142 | |
| 143 | if (process.env.NODE_ENV !== 'production') { |
| 144 | const queryHashes = queries.map( |
| 145 | (query) => this.#client.defaultQueryOptions(query).queryHash, |
| 146 | ) |
| 147 | if (new Set(queryHashes).size !== queryHashes.length) { |
| 148 | console.warn( |
| 149 | '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.', |
| 150 | ) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | notifyManager.batch(() => { |
| 155 | const prevObservers = this.#observers |
| 156 | |
| 157 | const newObserverMatches = this.#findMatchingObservers(this.#queries) |
| 158 | |
| 159 | // set options for the new observers to notify of changes |
| 160 | newObserverMatches.forEach((match) => |
| 161 | match.observer.setOptions(match.defaultedQueryOptions), |
| 162 | ) |
| 163 | |
| 164 | const newObservers = newObserverMatches.map((match) => match.observer) |
| 165 | const newResult = newObservers.map((observer) => |
| 166 | observer.getCurrentResult(), |
| 167 | ) |
| 168 | |
| 169 | const hasLengthChange = prevObservers.length !== newObservers.length |
| 170 | const hasIndexChange = newObservers.some( |
| 171 | (observer, index) => observer !== prevObservers[index], |
| 172 | ) |
| 173 | const hasStructuralChange = hasLengthChange || hasIndexChange |
| 174 | |
| 175 | const hasResultChange = hasStructuralChange |
| 176 | ? true |
| 177 | : newResult.some((result, index) => { |
| 178 | const prev = this.#result[index] |
| 179 | return !prev || !shallowEqualObjects(result, prev) |
| 180 | }) |
| 181 | |
| 182 | if (!hasStructuralChange && !hasResultChange) return |
| 183 | |
| 184 | if (hasStructuralChange) { |
| 185 | this.#observerMatches = newObserverMatches |
| 186 | this.#observers = newObservers |
| 187 | } |
| 188 | |
| 189 | this.#result = newResult |
| 190 | |
| 191 | if (!this.hasListeners()) return |
| 192 | |
| 193 | if (hasStructuralChange) { |
no test coverage detected