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

Method fetchOptimistic

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

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