UNPKG

@tanstack/query-core

Version:

The framework agnostic core that powers TanStack Query

526 lines (525 loc) • 22.5 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const require_timeoutManager = require("./timeoutManager.cjs"); const require_utils = require("./utils.cjs"); const require_environmentManager = require("./environmentManager.cjs"); const require_subscribable = require("./subscribable.cjs"); const require_focusManager = require("./focusManager.cjs"); const require_notifyManager = require("./notifyManager.cjs"); const require_query = require("./query.cjs"); //#region src/queryObserver.ts /** * 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) * }) * ``` */ var QueryObserver = class extends require_subscribable.Subscribable { #client; #currentQuery = void 0; #currentQueryInitialState = void 0; #currentResult = void 0; #currentResultState; #currentResultOptions; #selectError; #selectFn; #selectResult; #lastQueryWithDefinedData; #staleTimeoutId; #refetchIntervalId; #currentRefetchInterval; #trackedProps = /* @__PURE__ */ new Set(); constructor(client, options) { super(); this.options = options; this.#client = client; this.#selectError = null; 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. */ bindMethods() { this.refetch = this.refetch.bind(this); } onSubscribe() { if (this.listeners.size === 1) { this.#currentQuery.addObserver(this); if (shouldFetchOnMount(this.#currentQuery, this.options)) this.#executeFetch(); else this.updateResult(); this.#updateTimers(); } } onUnsubscribe() { 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() { 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() { 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() { this.listeners = /* @__PURE__ */ 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) { const prevOptions = this.options; const prevQuery = this.#currentQuery; this.options = this.#client.defaultQueryOptions(options); if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof require_utils.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 && !require_utils.shallowEqualObjects(this.options, prevOptions)) this.#client.getQueryCache().notify({ type: "observerOptionsUpdated", query: this.#currentQuery, observer: this }); const mounted = this.hasListeners(); if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) this.#executeFetch(); this.updateResult(); if (mounted && (this.#currentQuery !== prevQuery || require_utils.resolveQueryValue(this.options.enabled, this.#currentQuery) !== require_utils.resolveQueryValue(prevOptions.enabled, this.#currentQuery) || require_utils.resolveQueryValue(this.options.staleTime, this.#currentQuery) !== require_utils.resolveQueryValue(prevOptions.staleTime, this.#currentQuery))) this.#updateStaleTimeout(); const nextRefetchInterval = this.#computeRefetchInterval(); if (mounted && (this.#currentQuery !== prevQuery || require_utils.resolveQueryValue(this.options.enabled, this.#currentQuery) !== require_utils.resolveQueryValue(prevOptions.enabled, this.#currentQuery) || nextRefetchInterval !== this.#currentRefetchInterval)) this.#updateRefetchInterval(nextRefetchInterval); } /** * Computes the result the observer would produce for the given (already-defaulted) options * right now, building the underlying `Query` if it doesn't exist yet, without waiting for a * subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the * returned value is available synchronously, ahead of `setOptions` triggering an actual fetch. * @param options - The defaulted observer options to compute the result for. * @returns The result for the given options. */ getOptimisticResult(options) { const query = this.#client.getQueryCache().build(this.#client, options); const result = this.createResult(query, options); if (!require_utils.shallowEqualObjects(this.getCurrentResult(), result)) { this.#currentResult = result; this.#currentResultOptions = this.options; this.#currentResultState = this.#currentQuery.state; } return result; } /** * 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() { 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, onPropTracked) { return new Proxy(result, { get: (target, key) => { this.trackProp(key); onPropTracked?.(key); 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) { this.#trackedProps.add(key); } /** * Returns the `Query` instance this observer is currently observing. * @returns The observed query. */ getCurrentQuery() { 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 } = {}) { 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) { const defaultedOptions = this.#client.defaultQueryOptions(options); const query = this.#client.getQueryCache().build(this.#client, defaultedOptions); let unsubscribe = () => {}; let resolveEarly; 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 !== void 0) { unsubscribe(); resolve(this.createResult(query, defaultedOptions)); } }); }); return Promise.race([query.fetch(defaultedOptions).then(() => { const result = this.createResult(query, defaultedOptions); 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. */ fetch(fetchOptions) { return this.#executeFetch({ ...fetchOptions, cancelRefetch: fetchOptions.cancelRefetch ?? true }).then(() => { this.updateResult(); return this.#currentResult; }); } #executeFetch(fetchOptions) { this.#updateQuery(); let promise = this.#currentQuery.fetch(this.options, fetchOptions); if (!fetchOptions?.throwOnError) promise = promise.catch(require_utils.noop); return promise; } #shouldScheduleTimer(timeout) { return !require_environmentManager.isServer() && require_utils.resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && require_utils.isValidTimeout(timeout); } #updateStaleTimeout() { this.#clearStaleTimeout(); const staleTime = require_utils.resolveQueryValue(this.options.staleTime, this.#currentQuery); if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) return; const timeout = require_utils.timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + 1; this.#staleTimeoutId = require_timeoutManager.timeoutManager.setTimeout(() => { if (!this.#currentResult.isStale) this.updateResult(); }, timeout); } #computeRefetchInterval() { return require_utils.resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? false; } #updateRefetchInterval(nextInterval) { this.#clearRefetchInterval(); this.#currentRefetchInterval = nextInterval; if (this.#currentRefetchInterval === 0 || !this.#shouldScheduleTimer(this.#currentRefetchInterval)) return; this.#refetchIntervalId = require_timeoutManager.timeoutManager.setInterval(() => { if (this.options.refetchIntervalInBackground || require_focusManager.focusManager.isFocused()) this.#executeFetch(); }, this.#currentRefetchInterval); } #updateTimers() { this.#updateStaleTimeout(); this.#updateRefetchInterval(this.#computeRefetchInterval()); } #clearStaleTimeout() { if (this.#staleTimeoutId !== void 0) { require_timeoutManager.timeoutManager.clearTimeout(this.#staleTimeoutId); this.#staleTimeoutId = void 0; } } #clearRefetchInterval() { if (this.#refetchIntervalId !== void 0) { require_timeoutManager.timeoutManager.clearInterval(this.#refetchIntervalId); this.#refetchIntervalId = void 0; } } /** * 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. * @returns The computed result. */ createResult(query, options) { const prevQuery = this.#currentQuery; const prevOptions = this.options; const prevResult = this.#currentResult; const prevResultState = this.#currentResultState; const prevResultOptions = this.#currentResultOptions; const queryInitialState = query !== prevQuery ? query.state : this.#currentQueryInitialState; const { state } = query; let newState = { ...state }; let isPlaceholderData = false; let data; if (options._optimisticResults) { const mounted = this.hasListeners(); const fetchOnMount = !mounted && shouldFetchOnMount(query, options); const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions); if (fetchOnMount || fetchOptionally) newState = { ...newState, ...require_query.fetchState(state.data, query.options) }; if (options._optimisticResults === "isRestoring") newState.fetchStatus = "idle"; } let { error, errorUpdatedAt, status } = newState; data = newState.data; let skipSelect = false; if (options.placeholderData !== void 0 && data === void 0 && status === "pending") { let placeholderData; if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) { placeholderData = prevResult.data; skipSelect = true; } else placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(this.#lastQueryWithDefinedData?.state.data, this.#lastQueryWithDefinedData) : options.placeholderData; if (placeholderData !== void 0) { status = "success"; data = require_utils.replaceData(prevResult?.data, placeholderData, options); isPlaceholderData = true; } } if (options.select && data !== void 0 && !skipSelect) { if (prevResult && data === prevResultState?.data && options.select === this.#selectFn) data = this.#selectResult; else try { this.#selectFn = options.select; data = options.select(data); data = require_utils.replaceData(prevResult?.data, data, options); this.#selectResult = data; this.#selectError = null; } catch (selectError) { this.#selectError = selectError; } } else if (data === void 0) this.#selectError = null; if (this.#selectError) { error = this.#selectError; data = this.#selectResult; errorUpdatedAt = Date.now(); status = "error"; isPlaceholderData = false; } const isFetching = newState.fetchStatus === "fetching"; const isPending = status === "pending"; const isError = status === "error"; const isLoading = isPending && isFetching; const hasData = data !== void 0; return { status, fetchStatus: newState.fetchStatus, isPending, isSuccess: status === "success", isError, isInitialLoading: isLoading, 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: newState.fetchStatus === "paused", isPlaceholderData, isRefetchError: isError && hasData, isStale: isStale(query, options), refetch: this.refetch, isEnabled: require_utils.resolveQueryValue(options.enabled, query) !== false }; } /** * 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() { const prevResult = this.#currentResult; const nextResult = this.createResult(this.#currentQuery, this.options); this.#currentResultState = this.#currentQuery.state; this.#currentResultOptions = this.options; if (this.#currentResultState.data !== void 0) this.#lastQueryWithDefinedData = this.#currentQuery; if (require_utils.shallowEqualObjects(nextResult, prevResult)) return; this.#currentResult = nextResult; const shouldNotifyListeners = () => { if (!prevResult) return true; const { notifyOnChangeProps } = this.options; const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps; if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !this.#trackedProps.size) return true; const includedProps = new Set(notifyOnChangePropsValue ?? this.#trackedProps); if (this.options.throwOnError) includedProps.add("error"); return Object.keys(this.#currentResult).some((key) => { const typedKey = key; return this.#currentResult[typedKey] !== prevResult[typedKey] && includedProps.has(typedKey); }); }; const notifyListeners = shouldNotifyListeners(); require_notifyManager.notifyManager.batch(() => { if (notifyListeners) this.listeners.forEach((listener) => { listener(this.#currentResult); }); this.#client.getQueryCache().notify({ query: this.#currentQuery, type: "observerResultsUpdated" }); }); } #updateQuery() { const query = this.#client.getQueryCache().build(this.#client, this.options); if (query === this.#currentQuery) return; const prevQuery = this.#currentQuery; 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() { 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, options) { return require_utils.resolveQueryValue(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && require_utils.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, options) { return shouldLoadOnMount(query, options) || query.state.data !== void 0 && 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, options, field) { if (require_utils.resolveQueryValue(options.enabled, query) !== false && require_utils.resolveQueryValue(options.staleTime, query) !== "static") { const value = require_utils.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, prevQuery, options, prevOptions) { return (query !== prevQuery || require_utils.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, options) { return require_utils.resolveQueryValue(options.enabled, query) !== false && query.isStaleByTime(require_utils.resolveQueryValue(options.staleTime, query)); } //#endregion exports.QueryObserver = QueryObserver; //# sourceMappingURL=queryObserver.cjs.map