import type { CancelOptions, InvalidateOptions, InvalidateQueryFilters, Query, QueryFilters, QueryState, RefetchOptions, RefetchQueryFilters, ResetOptions, } from '@tanstack/react-query'; import type { OverriddenQueryFilterFields, typeCache } from './types.js'; import { QueryClient, skipToken, useQueryClient } from '@tanstack/react-query'; import { useState } from 'react'; export const noopSelector = (x: T): T => x; export const undefinedSelector = (): undefined => {}; export const noopKey = ['__NORMALIZED_REACT_QUERY__', 'SKIP']; // Suspense hooks cannot be disabled, so a disabled one reads this placeholder instead. // Passed as `initialData` (and never stale) so it never suspends, and users are never exposed to it. // A manual refetch resolves to the same placeholder. // Its own key keeps it out of the (data-less) query that disabled non-suspense hooks share. export const noopSuspenseKey = ['__NORMALIZED_REACT_QUERY__', 'SKIP_SUSPENSE']; // Shaped as if infinite. Required for infinite internals, and ignored for resource. export const noopData = { pages: [], pageParams: [], }; export const noopQueryFn = (): typeof noopData => noopData; /** * Options of a disabled query: it never fetches, and selects `undefined`. * Its key and selector are typed `never`, so they fit any query's options. */ export const skippedQueryOptions = { queryKey: noopKey as never, queryFn: skipToken, select: undefinedSelector as () => never, } as const; /** * Options of a disabled suspense query, which reads the placeholder `noopData` without suspending, and selects * `undefined`. Typed `never`, so they fit any query's options. */ export const skippedSuspenseQueryOptions = { queryKey: noopSuspenseKey as never, queryFn: noopQueryFn as () => never, initialData: noopData as never, staleTime: Infinity, select: undefinedSelector as () => never, }; /** * Page params of a disabled infinite query, which has no pages. */ export const skippedPageParams = { initialPageParam: null as never, getNextPageParam: undefinedSelector, getPreviousPageParam: undefinedSelector, }; /** * Adds `params` to the context Tanstack passes to `queryFn`, without reading any of its properties. * * Tanstack cancels a query when its last observer unmounts mid-fetch only if `signal` was read. * Spreading the context reads every property, so it would cancel (and later refetch) queries * whose `queryFn` never uses `signal`, e.g. every query under `StrictMode`. * * @param context - context Tanstack passes to `queryFn` * @param params - user provided params * @returns context with params */ export const withParams = ( context: TContext, params: TParams ): TContext & { params: TParams } => Object.defineProperties({ params }, Object.getOwnPropertyDescriptors(context)) as TContext & { params: TParams; }; /** * Client for a hook that is given a link, or nothing (disabled). * * Tanstack hooks stay on the client they first render with, so the hook keeps that client. * It starts on the link's client, or while disabled on the context client, which links from * `useNormalizedPrefetch*` hooks use. Without a `QueryClientProvider`, a disabled hook starts on * a new "dummy" client (to prevent any accidental "caching"). * * TanStack/query#12257 makes Tanstack hooks follow a client change. Once released, the hook can * follow the link's client instead of throwing. * * @param linkedClient - client of the link, or `null` while disabled * @returns query client to render the hook with * @throws {Error} if a link's client is not the one the hook started with, since Tanstack would keep reading the other client */ // @drop-when released https://github.com/TanStack/query/pull/12257 export const useLinkedQueryClient = (linkedClient: QueryClient | null): QueryClient => { let contextClient: QueryClient | null = null; try { // Called unconditionally, so hook order is stable. It only throws when there is no provider. contextClient = useQueryClient(); } catch { // No provider: use the linked client, or a new one } const [client] = useState(() => linkedClient ?? contextClient ?? new QueryClient()); if (linkedClient && linkedClient !== client) { throw new Error( 'A link was created with a different QueryClient than this hook first rendered with. Tanstack Query keeps the client a hook first renders with, so it would read a different cache. Render the hook inside a QueryClientProvider with the client the link was created with.' ); } return client; }; /** * Base class for TanstackQuery "resources" and "infinite" queries. * * A shared base class makes cross functionality like preloading easier, * and also takes over some of the "generic" cache facing functionality (like invalidation) * that aren't concerned with actual query implementation. * * @template TParams - user provided type for query input * @template TQueryKey - resulting TanstackQuery key from input * @template TData - return type from cache, without propagation */ export abstract class Queryable { /** * Used to access type parameters. * * __DO NOT USE__ */ declare public readonly [typeCache]?: { params: TParams; key: TQueryKey; data: TData; }; readonly #getKey: (params: TParams) => TQueryKey; protected constructor( option: | Queryable | { key: TQueryKey | ((params: TParams) => TQueryKey); } ) { if (option instanceof Queryable) { this.#getKey = option.#getKey; } else { const { key } = option; this.#getKey = typeof key === 'function' ? key : () => key; } } /** * Generate the key for the specific parameters to be passed to various TanstackQuery methods. * * @param params - user provided params to inject into callback * @returns query key */ public getKey(params: TParams): TQueryKey { return this.#getKey(params); } /** * Doesn't "do" anything, but ensures that params are in correct format, so that future references * can safely access. * * @param params - user provided params to inject into callback * @returns unmodified params */ // eslint-disable-next-line @typescript-eslint/class-methods-use-this -- uses class type public getParams(params: TParams): TParams { return params; } /** * Type safe wrapper around invalidating *only* the query defined by the given params. * * See [invalidateQueries](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientinvalidatequeries) * for expected behavior. * * For non-exact usage, call `invalidateQueries` directly with `queryKey: getKey()`. * * Does *not* directly impact propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @param options - invalidation options * @returns query is invalidated */ public async invalidateQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields>, options?: InvalidateOptions ): Promise { return queryClient.invalidateQueries( { ...filters, queryKey: this.getKey(params), exact: true, }, options ); } /** * Type safe wrapper around refetching *only* the query defined by the given params. * * See [refetchQueries](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientrefetchqueries) * for expected behavior. * * For non-exact usage, call `refetchQueries` directly with `queryKey: getKey()`. * * Does *not* directly impact propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @param options - refetch config * @returns query is refetched */ public async refetchQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields>, options?: RefetchOptions ): Promise { return queryClient.refetchQueries( { ...filters, queryKey: this.getKey(params), exact: true, }, options ); } /** * Type safe wrapper around canceling *only* the query defined by the given params. * * See [cancelQueries](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientcancelqueries) * for expected behavior. * * For non-exact usage, call `cancelQueries` directly with `queryKey: getKey()`. * * Does *not* directly impact propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @param options - cancellation options * @returns query is canceled */ public async cancelQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields>, options?: CancelOptions ): Promise { return queryClient.cancelQueries( { ...filters, queryKey: this.getKey(params), exact: true, }, options ); } /** * Type safe wrapper around removing *only* the query defined by the given params. * * See [removeQueries](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientremovequeries) * for expected behavior. * * For non-exact usage, call `removeQueries` directly with `queryKey: getKey()`. * * Does *not* directly impact propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact */ public removeQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields> ): void { queryClient.removeQueries({ ...filters, queryKey: this.getKey(params), exact: true, }); } /** * Type safe wrapper around resetting *only* the query defined by the given params. * * See [resetQueries](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientresetqueries) * for expected behavior. * * For non-exact usage, call `resetQueries` directly with `queryKey: getKey()`. * * Does *not* directly impact propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @param options - reset config * @returns query is reset */ public async resetQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields>, options?: ResetOptions ): Promise { return queryClient.resetQueries( { ...filters, queryKey: this.getKey(params), exact: true, }, options ); } /** * Type safe wrapper around checking whether *only* the query defined by the given params is fetching. * * See [isFetching](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientisfetching) * for more details. * * For non-exact usage, call `isFetching` directly with `queryKey: getKey()`. * * Does *not* represent propagated queries. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @returns query is reset */ public isFetching( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields> ): boolean { return ( queryClient.isFetching({ ...filters, queryKey: this.getKey(params), exact: true, }) !== 0 ); } /** * Load query data directly from cache if exists. * See [Tanstack docs](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetquerydata) * for better information. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @returns data from cache, if exists */ public getQueryData(queryClient: QueryClient, params: TParams): TData | undefined { return queryClient.getQueryData(this.getKey(params)); } /** * Expose internal query + cache state of query. * See [Tanstack docs](https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientgetquerystate) * for better information. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @returns data from cache, if exists */ public getQueryState( queryClient: QueryClient, params: TParams ): QueryState | undefined { return queryClient.getQueryState(this.getKey(params)); } /** * Expose internal query instance. * See [Tanstack docs](https://tanstack.com/query/latest/docs/reference/QueryCache#querycachefind) * for better information. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @param filters - [QueryFilters](https://tanstack.com/query/latest/docs/framework/react/guides/filters#query-filters), minus key + exact * @returns data from cache, if exists */ public getCachedQuery( queryClient: QueryClient, params: TParams, filters?: Omit, OverriddenQueryFilterFields> ): Query | undefined { return queryClient.getQueryCache().find({ ...filters, queryKey: this.getKey(params), exact: true, }); } /** * Returns true if query currently has data in cache, regardless of being stale. * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @returns data in cache */ public hasData(queryClient: QueryClient, params: TParams): boolean { return this.getQueryData(queryClient, params) !== undefined; } /** * Returns true if query exists, whether currently fetching, idle, stale... * * @param queryClient - instance of TanstackQuery QueryClient * @param params - user provided params to identify query * @returns query exists */ public hasState(queryClient: QueryClient, params: TParams): boolean { return this.getQueryState(queryClient, params) !== undefined; } }