MCPcopy Create free account
hub / github.com/TanStack/query / getOptimisticResult

Method getOptimisticResult

packages/query-core/src/queryObserver.ts:217–252  ·  view source on GitHub ↗
(
    options: DefaultedQueryObserverOptions<
      TQueryFnData,
      TError,
      TData,
      TQueryData,
      TQueryKey
    >,
  )

Source from the content-addressed store, hash-verified

215 }
216
217 getOptimisticResult(
218 options: DefaultedQueryObserverOptions<
219 TQueryFnData,
220 TError,
221 TData,
222 TQueryData,
223 TQueryKey
224 >,
225 ): QueryObserverResult<TData, TError> {
226 const query = this.#client.getQueryCache().build(this.#client, options)
227
228 const result = this.createResult(query, options)
229
230 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
231 // this assigns the optimistic result to the current Observer
232 // because if the query function changes, useQuery will be performing
233 // an effect where it would fetch again.
234 // When the fetch finishes, we perform a deep data cloning in order
235 // to reuse objects references. This deep data clone is performed against
236 // the `observer.currentResult.data` property
237 // When QueryKey changes, we refresh the query and get new `optimistic`
238 // result, while we leave the `observer.currentResult`, so when new data
239 // arrives, it finds the old `observer.currentResult` which is related
240 // to the old QueryKey. Which means that currentResult and selectData are
241 // out of sync already.
242 // To solve this, we move the cursor of the currentResult every time
243 // an observer reads an optimistic value.
244
245 // When keeping the previous data, the result doesn't change until new
246 // data arrives.
247 this.#currentResult = result
248 this.#currentResultOptions = this.options
249 this.#currentResultState = this.#currentQuery.state
250 }
251 return result
252 }
253
254 getCurrentResult(): QueryObserverResult<TData, TError> {
255 return this.#currentResult

Callers 15

constructorMethod · 0.95
QueryControllerClass · 0.45
syncClientMethod · 0.45
syncClientMethod · 0.45
runFunction · 0.45
getOptimisticResultFunction · 0.45
useBaseQueryFunction · 0.45
useQueriesFunction · 0.45
createBaseQueryFunction · 0.45
injectQueriesFunction · 0.45
useBaseQueryFunction · 0.45
useQueriesFunction · 0.45

Calls 5

createResultMethod · 0.95
getCurrentResultMethod · 0.95
shallowEqualObjectsFunction · 0.90
getQueryCacheMethod · 0.80
buildMethod · 0.45

Tested by

no test coverage detected