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

Method fetchOptimistic

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

410 * ```
411 */
412 fetchOptimistic(
413 options: QueryObserverOptions<
414 TQueryFnData,
415 TError,
416 TData,
417 TQueryData,
418 TQueryKey
419 >,
420 ): Promise<QueryObserverResult<TData, TError>> {
421 const defaultedOptions = this.#client.defaultQueryOptions(options)
422
423 const query = this.#client
424 .getQueryCache()
425 .build(this.#client, defaultedOptions)
426
427 let unsubscribe = () => {}
428 let resolveEarly:
429 | ((result: QueryObserverResult<TData, TError>) => void)
430 | undefined
431
432 const cachePromise = new Promise<QueryObserverResult<TData, TError>>(
433 (resolve) => {
434 resolveEarly = resolve
435 unsubscribe = this.#client.getQueryCache().subscribe((event) => {
436 if (
437 event.type === 'updated' &&
438 event.query.queryHash === query.queryHash &&
439 query.state.data !== undefined
440 ) {
441 unsubscribe()
442 resolve(this.createResult(query, defaultedOptions))
443 }
444 })
445 },
446 )
447
448 return Promise.race([
449 query
450 .fetch(defaultedOptions)
451 .then(() => {
452 const result = this.createResult(query, defaultedOptions)
453 // Settle the subscriber promise so both branches always settle.
454 // This value is ignored by Promise.race since the fetch branch already won.
455 resolveEarly?.(result)
456 return result
457 })
458 .finally(() => {
459 unsubscribe()
460 }),
461 cachePromise,
462 ])
463 }
464
465 /**
466 * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and,

Callers 7

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