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

Method fetchOptimistic

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

* Fetches a query defined by the given options without affecting this * observer's own tracked query or result, and returns a promise that * resolves with the `QueryObserverResult` for that fetch. This is useful * for prefetching data that another observer (e.g. a query about to be * nav

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

Source from the content-addressed store, hash-verified

393 * ```
394 */
395 fetchOptimistic(
396 options: QueryObserverOptions<
397 TQueryFnData,
398 TError,
399 TData,
400 TQueryData,
401 TQueryKey
402 >,
403 ): Promise<QueryObserverResult<TData, TError>> {
404 const defaultedOptions = this.#client.defaultQueryOptions(options)
405
406 const query = this.#client
407 .getQueryCache()
408 .build(this.#client, defaultedOptions)
409
410 let unsubscribe = () => {}
411 let resolveEarly:
412 | ((result: QueryObserverResult<TData, TError>) => void)
413 | undefined
414
415 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
416 (resolve) => {
417 resolveEarly = resolve
418 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
419 if (
420 event.type === 'updated' &&
421 event.query.queryHash === query.queryHash &&
422 query.state.data !== undefined
423 ) {
424 unsubscribe()
425 resolve(this.createResult(query, defaultedOptions))
426 }
427 })
428 },
429 )
430
431 return Promise.race([
432 query
433 .fetch()
434 .then(() => {
435 const result = this.createResult(query, defaultedOptions)
436 // Settle the subscriber promise so both branches always settle.
437 // This value is ignored by Promise.race since the fetch branch already won.
438 resolveEarly?.(result)
439 return result
440 })
441 .finally(() => {
442 unsubscribe()
443 }),
444 cachePromise,
445 ])
446 }
447
448 protected fetch(
449 fetchOptions: ObserverFetchOptions,

Callers 6

QueryControllerClass · 0.80
runFunction · 0.80
fetchOptimisticFunction · 0.80
fetchOptimisticFunction · 0.80

Calls 8

createResultMethod · 0.95
resolveFunction · 0.85
defaultQueryOptionsMethod · 0.80
getQueryCacheMethod · 0.80
unsubscribeFunction · 0.50
buildMethod · 0.45
subscribeMethod · 0.45
fetchMethod · 0.45

Tested by

no test coverage detected