* 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
>,
)
| 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, |
no test coverage detected