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