import { isServer as isServerEnvironment } from './environmentManager' import { focusManager } from './focusManager' import { notifyManager } from './notifyManager' import { fetchState } from './query' import { Subscribable } from './subscribable' import { timeoutManager } from './timeoutManager' import { isValidTimeout, noop, replaceData, resolveQueryValue, shallowEqualObjects, timeUntilStale, } from './utils' import type { FetchOptions, Query, QueryState } from './query' import type { QueryClient } from './queryClient' import type { ManagedTimerId } from './timeoutManager' import type { DefaultError, DefaultedQueryObserverOptions, PlaceholderDataFunction, QueryKey, QueryObserverBaseResult, QueryObserverOptions, QueryObserverOptionsBase, QueryObserverResult, QueryOptions, RefetchOptions, } from './types' type QueryObserverListener = ( result: QueryObserverResult, ) => void interface ObserverFetchOptions extends FetchOptions { throwOnError?: boolean } /** A cached view of an observer for one set of render options. */ export interface QueryObserverResultReader { /** Read the result, retaining its reference while all fields are unchanged. */ getSnapshot: () => TResult /** Apply this reader's options and reusable computation state after commit. */ commit: () => void } type ProjectionFailure = { error: TError errorUpdatedAt: number } /** * Selection and placeholder computation state shared by reads of the same result. * @internal */ export interface QueryObserverResultContext< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, > { /** The memo key and failure of the most recent selection. */ selection?: { key: { input: TQueryData select: (data: TQueryData) => TData structuralSharing: QueryOptions< TQueryFnData, TError, TQueryData, TQueryKey >['structuralSharing'] } failure?: ProjectionFailure } /** The last successful selection, used if selection fails. */ selected?: { data: TData query?: Query } /** The unselected placeholder or factory error. */ placeholder?: { key: { placeholderData: QueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey >['placeholderData'] structuralSharing: QueryOptions< TQueryFnData, TError, TQueryData, TQueryKey >['structuralSharing'] previousQuery: | Query | undefined previousState: QueryState | undefined previousOptions: | QueryOptions | undefined } sourceQuery?: Query input: TQueryData | undefined failure?: ProjectionFailure } } /** * Options supplied to an observer by a caller or already resolved by the client. * @internal */ export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > = | QueryObserverOptions | DefaultedQueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey > /** * A `QueryObserver` watches a single query in the `QueryCache` and computes a * `QueryObserverResult` from its state, recomputing and notifying subscribers * whenever the underlying query (or the observer's options) changes. It is * the primitive that framework adapters (e.g. `useQuery`) build their hooks * on top of, but it can also be used directly to observe and switch between * queries outside of any framework. * @example * ```ts * const observer = new QueryObserver(queryClient, { * queryKey: ['posts'], * queryFn: fetchPosts, * }) * * const unsubscribe = observer.subscribe((result) => { * console.log(result.data) * }) * ``` */ export class QueryObserver< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > extends Subscribable> { #client: QueryClient #currentQuery: Query = undefined! #currentQueryInitialState: QueryState = undefined! #currentResult: QueryObserverResult = undefined! #resultContext: QueryObserverResultContext< TQueryFnData, TError, TData, TQueryData, TQueryKey > = {} // This property keeps track of the last query with defined data. // It will be used to pass the previous data and query to the placeholder function between renders. #lastQueryWithDefinedData?: Query #staleTimeoutId?: ManagedTimerId #refetchIntervalId?: ManagedTimerId #currentRefetchInterval?: number | false #trackedProps = new Set() constructor( client: QueryClient, public options: ObserverOptionsInput< TQueryFnData, TError, TData, TQueryData, TQueryKey >, ) { super() this.#client = client this.bindMethods() this.setOptions(options) } /** * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured * from it. Subclasses override it to bind their own result methods as well. */ protected bindMethods(): void { this.refetch = this.refetch.bind(this) } protected override onSubscribe(): void { if (this.listeners.size === 1) { this.#currentQuery.addObserver(this) if (shouldFetchOnMount(this.#currentQuery, this.options)) { this.#executeFetch() } else { this.updateResult() } this.#updateTimers() } } protected override onUnsubscribe(): void { if (!this.hasListeners()) { this.destroy() } } /** * Returns whether the observed query is currently stale and configured * (via the `refetchOnReconnect` option) to refetch when the network * reconnects. * @returns `true` if the observer should refetch the query on reconnect. */ shouldFetchOnReconnect(): boolean { return shouldFetchOn( this.#currentQuery, this.options, this.options.refetchOnReconnect, ) } /** * Returns whether the observed query is currently stale and configured * (via the `refetchOnWindowFocus` option) to refetch when the window * regains focus. * @returns `true` if the observer should refetch the query on window focus. */ shouldFetchOnWindowFocus(): boolean { return shouldFetchOn( this.#currentQuery, this.options, this.options.refetchOnWindowFocus, ) } /** * Stops observing the current query: clears all listeners, cancels the * stale and refetch-interval timers, and removes this observer from the * query it was observing. */ destroy(): void { this.listeners = new Set() this.#clearStaleTimeout() this.#clearRefetchInterval() this.#currentQuery.removeObserver(this) } /** * Updates the observer's options. This will re-resolve the query being * observed (switching to a different query if the `queryKey` changed), * trigger a fetch if the new options require one and the observer has * subscribers, recompute the current result, and reschedule the stale and * refetch-interval timers as needed. * @param options - The new observer options. They are defaulted with {@link * QueryClient#defaultQueryOptions} before being applied. * @throws {Error} If `enabled` is neither a boolean nor a function. * @example * ```ts * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) * // later: switch to a different query, reusing the same observer * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) * ``` */ setOptions( options: ObserverOptionsInput< TQueryFnData, TError, TData, TQueryData, TQueryKey >, ): void { const prevOptions = this.options const prevQuery = this.#currentQuery this.options = this.#client.defaultQueryOptions(options) if ( this.options.enabled !== undefined && typeof this.options.enabled !== 'boolean' && typeof this.options.enabled !== 'function' && typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== 'boolean' ) { throw new Error( 'Expected enabled to be a boolean or a callback that returns a boolean', ) } this.#updateQuery() this.#currentQuery.setOptions(this.options) if ( prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions) ) { this.#client.getQueryCache().notify({ type: 'observerOptionsUpdated', query: this.#currentQuery, observer: this, }) } const mounted = this.hasListeners() // Fetch if there are subscribers if ( mounted && shouldFetchOptionally( this.#currentQuery, prevQuery, this.options, prevOptions, ) ) { this.#executeFetch() } // Update result this.updateResult() // Update stale interval if needed if ( mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || resolveQueryValue(this.options.staleTime, this.#currentQuery) !== resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) ) { this.#updateStaleTimeout() } const nextRefetchInterval = this.#computeRefetchInterval() // Update refetch interval if needed if ( mounted && (this.#currentQuery !== prevQuery || resolveQueryValue(this.options.enabled, this.#currentQuery) !== resolveQueryValue(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval) ) { this.#updateRefetchInterval(nextRefetchInterval) } } /** * Creates a result reader that captures the supplied query options. * Reads cache the complete result locally and retain its reference while its * fields are unchanged. They do not update this observer's committed result, * options, or selection state. Missing queries are built in the query cache. * Call `commit` after the render commits to apply the options and reuse the * reader's computation. An abandoned reader needs no cleanup. * @param options - The defaulted options used to read and commit the query result. * @returns A reader with local snapshot and computation caches. */ createResultReader( options: DefaultedQueryObserverOptions< TQueryFnData, TError, TData, TQueryData, TQueryKey >, ): QueryObserverResultReader> { const readerOptions = { ...options } const { select, structuralSharing } = readerOptions const context = { ...this.#resultContext } let result = this.#currentResult const getSnapshot = () => { const query = this.#client .getQueryCache() .build(this.#client, readerOptions) const { selection, selected } = this.#resultContext const input = query.state.data // A query update may already have selected this data. if ( input !== undefined && select && shallowEqualObjects( { input, select, structuralSharing }, selection?.key, ) ) { context.selection = selection context.selected = selected } const nextResult = this.createResult( query, readerOptions, context, result, ) if (!shallowEqualObjects(nextResult, result)) { result = nextResult } return result } return { getSnapshot, commit: () => { // Reuse selections computed since the last read. getSnapshot() this.#resultContext = { ...context } this.setOptions(readerOptions) }, } } /** * Returns the most recently computed `QueryObserverResult` for the * observed query. This is a point-in-time read; to be notified of updates * as they happen, subscribe to the observer instead (its inherited * `subscribe` method). * @returns The observer's latest result. * @example * ```ts * const result = observer.getCurrentResult() * console.log(result.status, result.data) * ``` */ getCurrentResult(): QueryObserverResult { return this.#currentResult } /** * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on * properties you actually read" behavior. * @param result - The result to wrap. * @param onPropTracked - Called with the name of each property that is read. * @returns A proxy of `result` that tracks property reads. */ trackResult( result: QueryObserverResult, onPropTracked?: (key: keyof QueryObserverResult) => void, ): QueryObserverResult { return new Proxy(result, { get: (target, key) => { this.trackProp(key as keyof QueryObserverResult) onPropTracked?.(key as keyof QueryObserverResult) return Reflect.get(target, key) }, }) } /** * Records that the given `QueryObserverResult` property was read, so a subsequent update only * notifies this observer if a tracked property actually changed. Normally called indirectly via * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property * access themselves (e.g. through their own reactivity system) instead of via the proxy. * @param key - The name of the property that was read. */ trackProp(key: keyof QueryObserverResult) { this.#trackedProps.add(key) } /** * Returns the `Query` instance this observer is currently observing. * @returns The observed query. */ getCurrentQuery(): Query { return this.#currentQuery } /** * Refetches the observed query and returns a promise that resolves with * the resulting `QueryObserverResult`. * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling * it, and `throwOnError` to `true` to reject when the refetch fails. * @returns A promise that resolves with the result after the refetch. * @example * ```ts * const result = await observer.refetch({ cancelRefetch: false }) * console.log(result.data) * ``` */ refetch( options: RefetchOptions = {}, ): Promise> { return this.fetch(options) } /** * 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 * navigated to) will need, ahead of time. * @param options - The observer options of the query to fetch. * @returns A promise that resolves with the result for the fetched query. * @example * ```ts * const result = await observer.fetchOptimistic({ * queryKey: ['posts', 2], * queryFn: () => fetchPost(2), * }) * console.log(result.data) * ``` */ fetchOptimistic( options: ObserverOptionsInput< TQueryFnData, TError, TData, TQueryData, TQueryKey >, ): Promise> { const defaultedOptions = this.#client.defaultQueryOptions(options) const query = this.#client .getQueryCache() .build(this.#client, defaultedOptions) let unsubscribe = () => {} let resolveEarly: | ((result: QueryObserverResult) => void) | undefined const cachePromise = new Promise>( (resolve) => { resolveEarly = resolve unsubscribe = this.#client.getQueryCache().subscribe((event) => { if ( event.type === 'updated' && event.query.queryHash === query.queryHash && query.state.data !== undefined ) { unsubscribe() resolve(this.createResult(query, defaultedOptions)) } }) }, ) return Promise.race([ query .fetch(defaultedOptions) .then(() => { const result = this.createResult(query, defaultedOptions) // Resolve the cache wait when the fetch succeeds. resolveEarly?.(result) return result }) .finally(() => { unsubscribe() }), cachePromise, ]) } /** * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, * in `InfiniteQueryObserver`, to fetch more pages. * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. * @returns A promise that resolves with the updated result. */ protected fetch( fetchOptions: ObserverFetchOptions, ): Promise> { return this.#executeFetch({ ...fetchOptions, cancelRefetch: fetchOptions.cancelRefetch ?? true, }).then(() => { this.updateResult() return this.#currentResult }) } #executeFetch( fetchOptions?: Omit, ): Promise { // Make sure we reference the latest query as the current one might have been removed this.#updateQuery() // Fetch let promise: Promise = this.#currentQuery.fetch( this.options, fetchOptions, ) if (!fetchOptions?.throwOnError) { promise = promise.catch(noop) } return promise } #shouldScheduleTimer(timeout: unknown): timeout is number { return ( !isServerEnvironment() && resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && isValidTimeout(timeout) ) } #updateStaleTimeout(): void { this.#clearStaleTimeout() const staleTime = resolveQueryValue( this.options.staleTime, this.#currentQuery, ) if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { return } const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) // The timeout is sometimes triggered 1 ms before the stale time expiration. // To mitigate this issue we always add 1 ms to the timeout. const timeout = time + 1 this.#staleTimeoutId = timeoutManager.setTimeout(() => { if (!this.#currentResult.isStale) { this.updateResult() } }, timeout) } #computeRefetchInterval() { return ( resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? false ) } #updateRefetchInterval(nextInterval: number | false): void { this.#clearRefetchInterval() this.#currentRefetchInterval = nextInterval if ( this.#currentRefetchInterval === 0 || !this.#shouldScheduleTimer(this.#currentRefetchInterval) ) { return } this.#refetchIntervalId = timeoutManager.setInterval(() => { if ( this.options.refetchIntervalInBackground || focusManager.isFocused() ) { this.#executeFetch() } }, this.#currentRefetchInterval) } #updateTimers(): void { this.#updateStaleTimeout() this.#updateRefetchInterval(this.#computeRefetchInterval()) } #clearStaleTimeout(): void { if (this.#staleTimeoutId !== undefined) { timeoutManager.clearTimeout(this.#staleTimeoutId) this.#staleTimeoutId = undefined } } #clearRefetchInterval(): void { if (this.#refetchIntervalId !== undefined) { timeoutManager.clearInterval(this.#refetchIntervalId) this.#refetchIntervalId = undefined } } #resolvePlaceholder( options: QueryObserverOptionsBase< TQueryFnData, TError, TData, TQueryData, TQueryKey >, previousResultData: TData | undefined, context = this.#resultContext, ) { const { placeholderData, structuralSharing } = options const memo = context.placeholder const previousQuery = this.#lastQueryWithDefinedData const previousState = previousQuery?.state const key = { placeholderData, structuralSharing, previousQuery, previousState, previousOptions: previousQuery?.options, } if (shallowEqualObjects(key, memo?.key)) { return memo } let failure: ProjectionFailure | undefined let input: TQueryData | undefined let sourceQuery: typeof previousQuery if (typeof placeholderData === 'function') { try { input = ( placeholderData as unknown as PlaceholderDataFunction< TQueryFnData, TError, TQueryData, TQueryKey > )(previousState?.data, previousQuery) } catch (error) { failure = { error: error as TError, errorUpdatedAt: Date.now() } } if (previousState?.data !== undefined) { sourceQuery = previousQuery } } else { input = placeholderData } if (input !== undefined) { input = replaceData( previousResultData, input as unknown, options, ) as TQueryData } return input !== undefined || failure ? { key, input, sourceQuery, failure } : undefined } /** * Computes the result for a query and options from the query's state, applying `select`, * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. * @param query - The query to compute the result for. * @param options - The observer options to compute the result with. * @param context - The selection and placeholder state reused between computations. * @param prevResult - The previous result used for structural sharing. * @returns The computed result. */ protected createResult( query: Query, options: QueryObserverOptionsBase< TQueryFnData, TError, TData, TQueryData, TQueryKey >, context = this.#resultContext, prevResult = this.#currentResult as | QueryObserverResult | undefined, ): QueryObserverResult { const prevQuery = this.#currentQuery const prevOptions = this.options const queryChange = query !== prevQuery const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState const { state } = query const fetchOptimistically = options._optimisticResults && (this.hasListeners() ? shouldFetchOptionally(query, prevQuery, options, prevOptions) : shouldFetchOnMount(query, options)) const newState = fetchOptimistically ? { ...state, ...fetchState(state.data, query.options) } : state const fetchStatus = options._optimisticResults === 'isRestoring' ? 'idle' : newState.fetchStatus const selectedQuery = context.selected?.query if (selectedQuery && selectedQuery.state.data === undefined) { context.selected = undefined // Keep a cached error stable, but a successful selection needs its data. if (!context.selection?.failure) { context.selection = undefined } } const { placeholderData, select, structuralSharing } = options if ( newState.data === undefined && newState.status === 'pending' && placeholderData !== undefined ) { context.placeholder = this.#resolvePlaceholder( options, prevResult?.data, context, ) } else { context.placeholder = undefined } const placeholder = context.placeholder const input = placeholder ? placeholder.input : newState.data if (!select || input === undefined) { context.selection = undefined } else { const key = { input, select, structuralSharing } if (!shallowEqualObjects(key, context.selection?.key)) { try { const data = replaceData(prevResult?.data, select(input), options) context.selected = { data, query: placeholder ? placeholder.sourceQuery : query, } context.selection = { key } } catch (error) { context.selection = { key, failure: { error: error as TError, errorUpdatedAt: Date.now(), }, } } } } const failure = placeholder?.failure ?? context.selection?.failure const data = context.selection ? context.selected?.data : (input as unknown as TData | undefined) const isPlaceholderData = placeholder !== undefined && input !== undefined && !failure const { error, errorUpdatedAt } = failure ?? newState const status = failure ? 'error' : isPlaceholderData ? 'success' : newState.status const isFetching = fetchStatus === 'fetching' const isPending = status === 'pending' const isError = status === 'error' const isLoading = isPending && isFetching const hasData = data !== undefined const result: QueryObserverBaseResult = { status, fetchStatus, isPending, isSuccess: status === 'success', isError, isLoading, data, dataUpdatedAt: newState.dataUpdatedAt, error, errorUpdatedAt, failureCount: newState.fetchFailureCount, failureReason: newState.fetchFailureReason, errorUpdateCount: newState.errorUpdateCount, isFetched: query.isFetched(), isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount, isFetching, isRefetching: isFetching && !isPending, isLoadingError: isError && !hasData, isPaused: fetchStatus === 'paused', isPlaceholderData, isRefetchError: isError && hasData, isStale: isStale(query, options), refetch: this.refetch, isEnabled: resolveQueryValue(options.enabled, query) !== false, } const nextResult = result as QueryObserverResult return nextResult } /** * Recomputes and stores the current result from the current query/options, notifying listeners * if it changed. Framework adapters call this right after subscribing to make sure no query * update was missed in the gap between creating the observer and subscribing to it. */ updateResult(): void { const prevResult = this.#currentResult as | QueryObserverResult | undefined const nextResult = this.createResult(this.#currentQuery, this.options) if (this.#currentQuery.state.data !== undefined) { this.#lastQueryWithDefinedData = this.#currentQuery } // Only notify and update result if something has changed if (shallowEqualObjects(nextResult, prevResult)) { return } this.#currentResult = nextResult const shouldNotifyListeners = (): boolean => { if (!prevResult) { return true } const { notifyOnChangeProps } = this.options if ( notifyOnChangeProps === 'all' || (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) ) { return true } if ( this.options.throwOnError && this.#currentResult.error !== prevResult.error ) { return true } if (notifyOnChangeProps === 'none') { return false } for (const key of this.#trackedProps) { if (this.#currentResult[key] !== prevResult[key]) { return true } } return false } const notifyListeners = shouldNotifyListeners() notifyManager.batch(() => { // First, trigger the listeners if (notifyListeners) { this.listeners.forEach((listener) => { listener(this.#currentResult) }) } // Then the cache listeners this.#client.getQueryCache().notify({ query: this.#currentQuery, type: 'observerResultsUpdated', }) }) } #updateQuery(): void { const query = this.#client.getQueryCache().build(this.#client, this.options) if (query === this.#currentQuery) { return } const prevQuery = this.#currentQuery as | Query | undefined this.#currentQuery = query this.#currentQueryInitialState = query.state if (this.hasListeners()) { prevQuery?.removeObserver(this) query.addObserver(this) } } /** * Updates the observer's result when the observed query changes, and reschedules its timers if it * has listeners. * @internal */ onQueryUpdate(): void { this.updateResult() if (this.hasListeners()) { this.#updateTimers() } } } /** * Checks whether a query has no data yet and should do its initial load when an observer mounts. * @param query - The query to check. * @param options - The observer options. * @returns `true` if the query is enabled, has no data, and isn't in an error state with * `retryOnMount: false`. */ function shouldLoadOnMount( query: Query, options: QueryObserverOptionsBase, ): boolean { return ( resolveQueryValue(options.enabled, query) !== false && query.state.data === undefined && !( query.state.status === 'error' && resolveQueryValue(options.retryOnMount, query) === false ) ) } /** * Checks whether a query should fetch when an observer mounts: either for its initial load, or * because it has data and `refetchOnMount` asks for a refetch. * @param query - The query to check. * @param options - The observer options. * @returns `true` if the query should fetch on mount. */ function shouldFetchOnMount( query: Query, options: QueryObserverOptionsBase, ): boolean { return ( shouldLoadOnMount(query, options) || (query.state.data !== undefined && shouldFetchOn(query, options, options.refetchOnMount)) ) } /** * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or * `refetchOnReconnect` option. * @param query - The query to check. * @param options - The observer options. * @param field - The value of the option to check. * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not * `false` and the query is stale. */ function shouldFetchOn( query: Query, options: QueryObserverOptionsBase, field: (typeof options)['refetchOnMount'] & (typeof options)['refetchOnWindowFocus'] & (typeof options)['refetchOnReconnect'], ) { if ( resolveQueryValue(options.enabled, query) !== false && resolveQueryValue(options.staleTime, query) !== 'static' ) { const value = resolveQueryValue(field, query) return value === 'always' || (value !== false && isStale(query, options)) } return false } /** * Checks whether a query should fetch after the observer's options change. * @param query - The query observed with the new options. * @param prevQuery - The query observed with the previous options. * @param options - The new observer options. * @param prevOptions - The previous observer options. * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an * error state, and it is stale. */ function shouldFetchOptionally( query: Query, prevQuery: Query, options: QueryObserverOptionsBase, prevOptions: QueryObserverOptionsBase, ): boolean { return ( (query !== prevQuery || resolveQueryValue(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options) ) } /** * Checks whether a query is stale for the given observer options. * @param query - The query to check. * @param options - The observer options, whose `enabled` and `staleTime` are used. * @returns `true` if the query is enabled and its data is stale for `staleTime`. */ function isStale( query: Query, options: QueryObserverOptionsBase, ): boolean { return ( resolveQueryValue(options.enabled, query) !== false && query.isStaleByTime(resolveQueryValue(options.staleTime, query)) ) }