* Fetches the query, i.e. runs its `queryFn` (through any configured * retryer/behavior) and updates the query's state with the result. * - If a fetch is already in flight, returns its promise instead of * starting a new one, unless `fetchOptions.cancelRefetch` is set and the * query
(
options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
fetchOptions?: FetchOptions<TQueryFnData>,
)
| 707 | * instead. |
| 708 | */ |
| 709 | async fetch( |
| 710 | options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>, |
| 711 | fetchOptions?: FetchOptions<TQueryFnData>, |
| 712 | ): Promise<TData> { |
| 713 | if ( |
| 714 | this.state.fetchStatus !== 'idle' && |
| 715 | // If the promise in the retryer is already rejected, we have to definitely |
| 716 | // re-start the fetch; there is a chance that the query is still in a |
| 717 | // pending state when that happens |
| 718 | this.#retryer?.status() !== 'rejected' |
| 719 | ) { |
| 720 | if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { |
| 721 | // Silently cancel current fetch if the user wants to cancel refetch |
| 722 | this.cancel({ silent: true }) |
| 723 | } else if (this.#retryer && this.#fetchPromise) { |
| 724 | // make sure that retries that were potentially cancelled due to unmounts can continue |
| 725 | this.#retryer.continueRetry() |
| 726 | // Return current promise if we are already fetching |
| 727 | return this.#fetchPromise |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | // Update config if passed, otherwise the config from the last execution is used |
| 732 | if (options) { |
| 733 | this.setOptions(options) |
| 734 | } |
| 735 | |
| 736 | // Use the options from the first observer with a query function if no function is found. |
| 737 | // This can happen when the query is hydrated or created with setQueryData. |
| 738 | if (!this.options.queryFn) { |
| 739 | const observer = this.observers.find((x) => x.options.queryFn) |
| 740 | if (observer) { |
| 741 | this.setOptions(observer.options) |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | if (process.env.NODE_ENV !== 'production') { |
| 746 | if (!Array.isArray(this.options.queryKey)) { |
| 747 | console.error( |
| 748 | `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, |
| 749 | ) |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | const abortController = new AbortController() |
| 754 | |
| 755 | // Adds an enumerable signal property to the object that |
| 756 | // which sets abortSignalConsumed to true when the signal |
| 757 | // is read. |
| 758 | const addSignalProperty = (object: object) => { |
| 759 | Object.defineProperties(object, { |
| 760 | [fetchSignal]: { value: abortController.signal, enumerable: true }, |
| 761 | signal: { |
| 762 | enumerable: true, |
| 763 | get: () => { |
| 764 | this.#abortSignalConsumed = true |
| 765 | return abortController.signal |
| 766 | }, |
no test coverage detected