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

Method getOptimisticResult

packages/query-core/src/queryObserver.ts:272–307  ·  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

270 * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
271 */
272 getOptimisticResult(
273 options: DefaultedQueryObserverOptions<
274 TQueryFnData,
275 TError,
276 TData,
277 TQueryData,
278 TQueryKey
279 >,
280 ): QueryObserverResult<TData, TError> {
281 const query = this.#client.getQueryCache().build(this.#client, options)
282
283 const result = this.createResult(query, options)
284
285 if (!shallowEqualObjects(this.getCurrentResult(), result)) {
286 // this assigns the optimistic result to the current Observer
287 // because if the query function changes, useQuery will be performing
288 // an effect where it would fetch again.
289 // When the fetch finishes, we perform a deep data cloning in order
290 // to reuse objects references. This deep data clone is performed against
291 // the `observer.currentResult.data` property
292 // When QueryKey changes, we refresh the query and get new `optimistic`
293 // result, while we leave the `observer.currentResult`, so when new data
294 // arrives, it finds the old `observer.currentResult` which is related
295 // to the old QueryKey. Which means that currentResult and selectData are
296 // out of sync already.
297 // To solve this, we move the cursor of the currentResult every time
298 // an observer reads an optimistic value.
299
300 // When keeping the previous data, the result doesn't change until new
301 // data arrives.
302 this.#currentResult = result
303 this.#currentResultOptions = this.options
304 this.#currentResultState = this.#currentQuery.state
305 }
306 return result
307 }
308
309 /**
310 * 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
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