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

Method getOptimisticResult

packages/query-core/src/queryObserver.ts:281–316  ·  view source on GitHub ↗

* Computes the result the observer would produce for the given (already-defaulted) options * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the * returned va

(
    options: DefaultedQueryObserverOptions<
      TQueryFnData,
      TError,
      TData,
      TQueryData,
      TQueryKey
    >,
  )

Source from the content-addressed store, hash-verified

279 * @returns The result for the given options.
280 */
281 getOptimisticResult(
282 options: DefaultedQueryObserverOptions<
283 TQueryFnData,
284 TError,
285 TData,
286 TQueryData,
287 TQueryKey
288 >,
289 ): QueryObserverResult<TData, TError> {
290 const query = this.#client.getQueryCache().build(this.#client, options)
291
292 const result = this.createResult(query, options)
293
294 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
295 // this assigns the optimistic result to the current Observer
296 // because if the query function changes, useQuery will be performing
297 // an effect where it would fetch again.
298 // When the fetch finishes, we perform a deep data cloning in order
299 // to reuse objects references. This deep data clone is performed against
300 // the `observer.currentResult.data` property
301 // When QueryKey changes, we refresh the query and get new `optimistic`
302 // result, while we leave the `observer.currentResult`, so when new data
303 // arrives, it finds the old `observer.currentResult` which is related
304 // to the old QueryKey. Which means that currentResult and selectData are
305 // out of sync already.
306 // To solve this, we move the cursor of the currentResult every time
307 // an observer reads an optimistic value.
308
309 // When keeping the previous data, the result doesn't change until new
310 // data arrives.
311 this.#currentResult = result
312 this.#currentResultOptions = this.options
313 this.#currentResultState = this.#currentQuery.state
314 }
315 return result
316 }
317
318 /**
319 * Returns the most recently computed `QueryObserverResult` for the

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
useBaseQueryFunction · 0.45
useQueriesFunction · 0.45
injectBaseQueryFunction · 0.45
injectQueriesFunction · 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