diff --git a/.changeset/v6-infinite-fetch-behavior.md b/.changeset/v6-infinite-fetch-behavior.md new file mode 100644 index 00000000000..8989eee9987 --- /dev/null +++ b/.changeset/v6-infinite-fetch-behavior.md @@ -0,0 +1,8 @@ +--- +'@tanstack/query-core': major +'@tanstack/react-query': major +'@tanstack/preact-query': major +'@tanstack/vue-query': major +--- + +Replace `queryClient.infiniteQuery(options)` with `infiniteQuery(queryClient, options)`, imported from the adapter package or `@tanstack/query-core`. The Vue export accepts reactive options. Infinite queries keep the same cache entries and can still refetch after hydration before an observer mounts. Bundles that use only ordinary queries can omit the pagination implementation. diff --git a/docs/framework/react/guides/prefetching.md b/docs/framework/react/guides/prefetching.md index 130dae92775..3de57082f0a 100644 --- a/docs/framework/react/guides/prefetching.md +++ b/docs/framework/react/guides/prefetching.md @@ -60,18 +60,16 @@ Pass `getNextPageParam` when you prefetch an infinite query. On an empty cache, [//]: # 'ExamplePrefetchInfiniteQuery' ```tsx -import { noop } from '@tanstack/react-query' +import { infiniteQuery, noop } from '@tanstack/react-query' const prefetchProjects = async () => { - await queryClient - .infiniteQuery({ - queryKey: ['projects'], - queryFn: fetchProjects, - initialPageParam: 0, - getNextPageParam: (lastPage, pages) => lastPage.nextCursor, - pages: 3, // prefetch the first 3 pages - }) - .catch(noop) + await infiniteQuery(queryClient, { + queryKey: ['projects'], + queryFn: fetchProjects, + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage.nextCursor, + pages: 3, // prefetch the first 3 pages + }).catch(noop) } ``` diff --git a/docs/framework/vue/guides/prefetching.md b/docs/framework/vue/guides/prefetching.md index be51a758a21..c705ba173ac 100644 --- a/docs/framework/vue/guides/prefetching.md +++ b/docs/framework/vue/guides/prefetching.md @@ -3,7 +3,7 @@ id: prefetching title: Prefetching --- -If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed. If this is the case, use `queryClient.query` or `queryClient.infiniteQuery` to warm the cache ahead of time: +If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed. If this is the case, use `queryClient.query` or `infiniteQuery(queryClient, options)` to warm the cache ahead of time: [//]: # 'ExamplePrefetching' diff --git a/docs/framework/vue/guides/ssr.md b/docs/framework/vue/guides/ssr.md index 1a3f5394060..937c7b12d86 100644 --- a/docs/framework/vue/guides/ssr.md +++ b/docs/framework/vue/guides/ssr.md @@ -52,7 +52,7 @@ export default defineNuxtPlugin((nuxt) => { Now you are ready to prefetch some data in your pages with `onServerPrefetch`. -- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense` +- Prefetch all the queries that you need with `queryClient.query`, `infiniteQuery(queryClient, options)`, or `suspense` ```ts export default defineComponent({ @@ -112,7 +112,7 @@ Now you are ready to prefetch some data in your pages with `onServerPrefetch`. - Use `useContext` to get nuxt context - Use `useQueryClient` to get server-side instance of `queryClient` -- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense` +- Prefetch all the queries that you need with `queryClient.query`, `infiniteQuery(queryClient, options)`, or `suspense` - Dehydrate `queryClient` to the `nuxtContext` ```vue diff --git a/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts b/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts index cd9e839a400..1346ee14d07 100644 --- a/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts +++ b/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + dataTagSymbol, + infiniteQuery, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { infiniteQueryOptions } from '../infinite-query-options' @@ -73,7 +78,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -87,7 +92,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -101,7 +106,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -114,7 +119,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/angular-query/src/infinite-query-options.ts b/packages/angular-query/src/infinite-query-options.ts index 384ed232ccd..bd88e6e931d 100644 --- a/packages/angular-query/src/infinite-query-options.ts +++ b/packages/angular-query/src/infinite-query-options.ts @@ -133,7 +133,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as - * `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options + * `infiniteQuery(queryClient, options)`. `options.queryKey` is required and is the query key to generate options * for. * * This overload is selected when `initialData` is known to be defined. @@ -200,7 +200,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as - * `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options + * `infiniteQuery(queryClient, options)`. `options.queryKey` is required and is the query key to generate options * for. * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to * `injectInfiniteQuery`. @@ -271,7 +271,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as - * `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options + * `infiniteQuery(queryClient, options)`. `options.queryKey` is required and is the query key to generate options * for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to * `injectInfiniteQuery`. diff --git a/packages/angular-query/src/inject-infinite-query.ts b/packages/angular-query/src/inject-infinite-query.ts index 17447cd2e50..a74421761d8 100644 --- a/packages/angular-query/src/inject-infinite-query.ts +++ b/packages/angular-query/src/inject-infinite-query.ts @@ -46,7 +46,7 @@ import type { * actions, or add conditions like `hasNextPage() && !isFetching()`. * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs - * like `queryClient.infiniteQuery`. + * like `infiniteQuery(queryClient, options)`. * @example * ```angular-ts * @Component({ @@ -107,7 +107,7 @@ export function injectInfiniteQuery< * shown below. * @see https://tanstack.com/query/latest/docs/framework/angular/guides/infinite-queries * @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs - * like `queryClient.infiniteQuery`. + * like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a button click: * ```angular-ts diff --git a/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts b/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts index 42c7b9067f0..503cdc6cb99 100644 --- a/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts +++ b/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts @@ -2,6 +2,7 @@ import { QueryClient, dataTagErrorSymbol, dataTagSymbol, + infiniteQuery, skipToken, } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' @@ -85,7 +86,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -98,7 +99,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -111,7 +112,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -123,7 +124,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/lit-query/src/__tests__/ssr.test.ts b/packages/lit-query/src/__tests__/ssr.test.ts index ef4c3a18f85..663147806d1 100644 --- a/packages/lit-query/src/__tests__/ssr.test.ts +++ b/packages/lit-query/src/__tests__/ssr.test.ts @@ -2,7 +2,12 @@ import { render } from '@lit-labs/ssr' import { collectResult } from '@lit-labs/ssr/lib/render-result.js' -import { QueryCache, QueryClient, noop } from '@tanstack/query-core' +import { + QueryCache, + QueryClient, + infiniteQuery, + noop, +} from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { LitElement, html } from 'lit' import { html as staticHtml, unsafeStatic } from 'lit/static-html.js' @@ -143,14 +148,12 @@ describe('Server Side Rendering', () => { } } - queryClient - .infiniteQuery({ - queryKey: key, - queryFn, - getNextPageParam: () => undefined, - initialPageParam: 0, - }) - .catch(noop) + infiniteQuery(queryClient, { + queryKey: key, + queryFn, + getNextPageParam: () => undefined, + initialPageParam: 0, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) const markup = await renderToString(Page) diff --git a/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx index 9b5d0206a45..742469ee6ca 100644 --- a/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + dataTagSymbol, + infiniteQuery, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { infiniteQueryOptions } from '../infiniteQueryOptions' @@ -84,7 +89,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -98,7 +103,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -112,7 +117,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -125,7 +130,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/preact-query/src/__tests__/ssr.test.tsx b/packages/preact-query/src/__tests__/ssr.test.tsx index 6c2662de990..4b64da4ce96 100644 --- a/packages/preact-query/src/__tests__/ssr.test.tsx +++ b/packages/preact-query/src/__tests__/ssr.test.tsx @@ -1,3 +1,4 @@ +import { infiniteQuery } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { renderToString } from 'preact-render-to-string' import { useState } from 'preact/hooks' @@ -188,14 +189,12 @@ describe('Server Side Rendering', () => { ) } - void queryClient - .infiniteQuery({ - queryKey: key, - queryFn, - getNextPageParam: () => undefined, - initialPageParam: 0, - }) - .catch(noop) + void infiniteQuery(queryClient, { + queryKey: key, + queryFn, + getNextPageParam: () => undefined, + initialPageParam: 0, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) const markup = renderToString( diff --git a/packages/preact-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/preact-query/src/__tests__/useInfiniteQuery.test-d.tsx index 82eaaaf3a0e..821dbb180ed 100644 --- a/packages/preact-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/preact-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + infiniteQuery as fetchInfiniteQuery, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { useInfiniteQuery } from '../useInfiniteQuery' @@ -19,7 +22,7 @@ describe('pageParam', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - queryClient.infiniteQuery({ + fetchInfiniteQuery(queryClient, { queryKey: ['key'], queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/preact-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx b/packages/preact-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx index 9cdfbcba044..634740e8259 100644 --- a/packages/preact-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx +++ b/packages/preact-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx @@ -1,3 +1,4 @@ +import { infiniteQuery } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { fireEvent } from '@testing-library/preact' import { Suspense } from 'preact/compat' @@ -111,7 +112,7 @@ describe('usePrefetchInfiniteQuery', () => { allPages.length < data.length ? allPages.length : undefined, } - void queryClient.infiniteQuery({ ...queryOpts, pages: 3 }).catch(noop) + void infiniteQuery(queryClient, { ...queryOpts, pages: 3 }).catch(noop) await vi.advanceTimersByTimeAsync(30) queryOpts.queryFn.mockClear() diff --git a/packages/preact-query/src/infiniteQueryOptions.ts b/packages/preact-query/src/infiniteQueryOptions.ts index d4c3410482d..0fbdd6068ae 100644 --- a/packages/preact-query/src/infiniteQueryOptions.ts +++ b/packages/preact-query/src/infiniteQueryOptions.ts @@ -126,7 +126,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. @@ -188,7 +188,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -247,7 +247,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/packages/preact-query/src/types.ts b/packages/preact-query/src/types.ts index a9fd8822693..5d27745f703 100644 --- a/packages/preact-query/src/types.ts +++ b/packages/preact-query/src/types.ts @@ -100,7 +100,7 @@ export type UsePrefetchQueryOptions< } /** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(queryClient, options)`, * except `queryFn` is required unless a default query function has been defined. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. diff --git a/packages/preact-query/src/useInfiniteQuery.ts b/packages/preact-query/src/useInfiniteQuery.ts index 0f0471fb71c..79708dfe77e 100644 --- a/packages/preact-query/src/useInfiniteQuery.ts +++ b/packages/preact-query/src/useInfiniteQuery.ts @@ -32,7 +32,7 @@ import type { * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * ```tsx * import { useInfiniteQuery } from '@tanstack/preact-query' @@ -89,7 +89,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx @@ -212,7 +212,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx diff --git a/packages/preact-query/src/usePrefetchInfiniteQuery.tsx b/packages/preact-query/src/usePrefetchInfiniteQuery.tsx index 208d1ce2ee0..b3f5f2dde38 100644 --- a/packages/preact-query/src/usePrefetchInfiniteQuery.tsx +++ b/packages/preact-query/src/usePrefetchInfiniteQuery.tsx @@ -1,4 +1,4 @@ -import { noop } from '@tanstack/query-core' +import { infiniteQuery, noop } from '@tanstack/query-core' import { useQueryClient } from './QueryClientProvider' import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core' import type { UsePrefetchInfiniteQueryOptions } from './types' @@ -6,7 +6,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' /** * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass - * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(queryClient, options)`, though * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless * a default query function has been defined. * @@ -17,7 +17,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's * already there or already in flight. - * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(queryClient, options)`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. * @example @@ -63,6 +63,6 @@ export function usePrefetchInfiniteQuery< const client = useQueryClient(queryClient) if (!client.getQueryState(options.queryKey)) { - void client.infiniteQuery(options).catch(noop) + void infiniteQuery(client, options).catch(noop) } } diff --git a/packages/query-core/src/__tests__/hydration.test.tsx b/packages/query-core/src/__tests__/hydration.test.tsx index 716926661dd..1feb2c51f00 100644 --- a/packages/query-core/src/__tests__/hydration.test.tsx +++ b/packages/query-core/src/__tests__/hydration.test.tsx @@ -2,6 +2,7 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dehydrate, hydrate } from '../hydration' import { dehydrateQuery } from '../index' +import { infiniteQuery } from '../infiniteQuery' import { MutationCache } from '../mutationCache' import { QueryCache } from '../queryCache' import { QueryClient } from '../queryClient' @@ -1535,21 +1536,19 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = queryClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - items: [`page-${pageParam}`], - nextCursor: pageParam + 1, - })), - initialPageParam: 0, - getNextPageParam: (lastPage: { - items: Array - nextCursor: number - }) => lastPage.nextCursor, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(queryClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + items: [`page-${pageParam}`], + nextCursor: pageParam + 1, + })), + initialPageParam: 0, + getNextPageParam: (lastPage: { + items: Array + nextCursor: number + }) => lastPage.nextCursor, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) await prefetchPromise @@ -1576,19 +1575,17 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = queryClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - data: `page-${pageParam}`, - next: pageParam + 1, - })), - initialPageParam: 0, - getNextPageParam: (lastPage: { data: string; next: number }) => - lastPage.next, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(queryClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + data: `page-${pageParam}`, + next: pageParam + 1, + })), + initialPageParam: 0, + getNextPageParam: (lastPage: { data: string; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) await prefetchPromise @@ -1598,7 +1595,7 @@ describe('dehydration and rehydration', () => { const hydrationClient = new QueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, dehydrated) - const resultPromise = hydrationClient.infiniteQuery({ + const resultPromise = infiniteQuery(hydrationClient, { queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1620,19 +1617,17 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - items: [`item-${pageParam}`], - next: pageParam + 1, - })), - initialPageParam: 0, - getNextPageParam: (lastPage: { items: Array; next: number }) => - lastPage.next, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(serverClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + items: [`item-${pageParam}`], + next: pageParam + 1, + })), + initialPageParam: 0, + getNextPageParam: (lastPage: { items: Array; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) await prefetchPromise @@ -1657,19 +1652,17 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - items: [`page-${pageParam}`], - next: pageParam + 1, - })), - initialPageParam: 0, - getNextPageParam: (lastPage: { items: Array; next: number }) => - lastPage.next, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(serverClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + items: [`page-${pageParam}`], + next: pageParam + 1, + })), + initialPageParam: 0, + getNextPageParam: (lastPage: { items: Array; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) await prefetchPromise @@ -1686,7 +1679,7 @@ describe('dehydration and rehydration', () => { expect(beforeRefetch?.pages).toHaveLength(1) expect(beforeRefetch?.pageParams).toHaveLength(1) - const resultPromise = clientClient.infiniteQuery({ + const resultPromise = infiniteQuery(clientClient, { queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1710,19 +1703,17 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - data: `p${pageParam}`, - next: pageParam + 1, - })), - initialPageParam: 0, - getNextPageParam: (lastPage: { data: string; next: number }) => - lastPage.next, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(serverClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + data: `p${pageParam}`, + next: pageParam + 1, + })), + initialPageParam: 0, + getNextPageParam: (lastPage: { data: string; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) await prefetchPromise @@ -1743,20 +1734,18 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - items: [`item-${pageParam}`], - next: pageParam + 1, - })), - initialPageParam: 0, - pages: 2, - getNextPageParam: (lastPage: { items: Array; next: number }) => - lastPage.next, - }) - .catch(noop) + const prefetchPromise = infiniteQuery(serverClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + items: [`item-${pageParam}`], + next: pageParam + 1, + })), + initialPageParam: 0, + pages: 2, + getNextPageParam: (lastPage: { items: Array; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(20) await prefetchPromise @@ -1772,20 +1761,18 @@ describe('dehydration and rehydration', () => { }>(key) expect(beforeRefetch?.pages).toHaveLength(2) - const resultPromise = clientClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => - sleep(10).then(() => ({ - items: [`item-${pageParam}`], - next: pageParam + 1, - })), - initialPageParam: 0, - pages: 2, - getNextPageParam: (lastPage: { items: Array; next: number }) => - lastPage.next, - }) - .catch(noop) + const resultPromise = infiniteQuery(clientClient, { + queryKey: key, + queryFn: ({ pageParam }) => + sleep(10).then(() => ({ + items: [`item-${pageParam}`], + next: pageParam + 1, + })), + initialPageParam: 0, + pages: 2, + getNextPageParam: (lastPage: { items: Array; next: number }) => + lastPage.next, + }).catch(noop) await vi.advanceTimersByTimeAsync(20) const result = await resultPromise diff --git a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx index 68bf65c6e53..c2fb0498049 100644 --- a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx @@ -1,7 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, InfiniteQueryObserver, QueryClient } from '..' -import { infiniteQueryBehavior } from '../infiniteQueryBehavior' +import { infiniteQuery } from '../infiniteQuery' +import { infiniteBehavior } from '../infiniteQueryBehavior' import type { InfiniteData, InfiniteQueryObserverResult, @@ -345,7 +346,6 @@ describe('InfiniteQueryBehavior', () => { return pageParam }) - const behavior = infiniteQueryBehavior() const context = { client: queryClient, queryKey: key, @@ -366,7 +366,7 @@ describe('InfiniteQueryBehavior', () => { signal: abortController.signal, } - behavior.onFetch(context as any, {} as any) + infiniteBehavior.onFetch(context as any, {} as any) await expect(context.fetchFn()).rejects.toBe(abortController.signal.reason) expect(queryFn).toHaveBeenCalledTimes(1) @@ -480,13 +480,13 @@ describe('InfiniteQueryBehavior', () => { return String(pageParam) } - await queryClient.infiniteQuery({ + await infiniteQuery(queryClient, { queryKey: key, queryFn, initialPageParam: null, getNextPageParam: () => undefined, }) - await queryClient.infiniteQuery({ + await infiniteQuery(queryClient, { queryKey: key, queryFn, initialPageParam: 'replacement', diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx index ebe243dc35f..1555cf1206f 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx @@ -193,14 +193,6 @@ describe('infiniteQueryObserver', () => { }) }) - describe('_type', () => { - it('should only accept the infinite literal', () => { - expectTypeOf().toEqualTypeOf< - 'infinite' | undefined - >() - }) - }) - describe('behavior', () => { it('should be typed from the paged data it produces', () => { expectTypeOf< diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 4a9882cd9e3..e8cf8e0d148 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -232,10 +232,10 @@ describe('InfiniteQueryObserver', () => { const result = observer.createResultReader(options).getSnapshot() - expect(options._type).toBeUndefined() - expect( - queryClient.getQueryCache().get(options.queryHash)?.options._type, - ).toBe('infinite') + expect(options._infiniteBehavior).toBeUndefined() + expect(queryClient.getQueryCache().get(options.queryHash)?.queryType).toBe( + 'infinite', + ) expect(result).toMatchObject({ data: undefined, diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index c5222c584fa..59d2713b58f 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,4 +1,5 @@ import { assertType, describe, expectTypeOf, it } from 'vitest' +import { infiniteQuery } from '../infiniteQuery' import { QueryClient } from '../queryClient' import { skipToken } from '../utils' import type { Mutation } from '../mutation' @@ -404,7 +405,7 @@ describe('queryClient', () => { describe('infiniteQuery', () => { it('should allow passing select option', () => { - const result = new QueryClient().infiniteQuery({ + const result = infiniteQuery(new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, @@ -418,7 +419,7 @@ describe('queryClient', () => { }) it('should allow passing pages', async () => { - const result = await new QueryClient().infiniteQuery({ + const result = await infiniteQuery(new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), getNextPageParam: () => 1, @@ -444,7 +445,8 @@ describe('queryClient', () => { }) it('should allow passing getNextPageParam without pages', () => { - assertType>([ + assertType>([ + new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), @@ -455,7 +457,8 @@ describe('queryClient', () => { }) it('should require getNextPageParam even without pages', () => { - assertType>([ + assertType>([ + new QueryClient(), // @ts-expect-error Property 'getNextPageParam' is missing { queryKey: ['key'], @@ -467,7 +470,7 @@ describe('queryClient', () => { it('should default its page param to unknown', () => { const queryClient = new QueryClient() - const result = queryClient.infiniteQuery({ + const result = infiniteQuery(queryClient, { queryKey: ['key'], queryFn: () => Promise.resolve('string'), initialPageParam: 1, @@ -479,21 +482,21 @@ describe('queryClient', () => { >() type PageParam = Parameters< - typeof queryClient.infiniteQuery - >[0]['initialPageParam'] + typeof infiniteQuery + >[1]['initialPageParam'] expectTypeOf().toEqualTypeOf() }) it('should resolve with InfiniteData of the data type', async () => { const queryClient = new QueryClient() - const data = await queryClient.infiniteQuery(typedInfiniteQueryOptions) + const data = await infiniteQuery(queryClient, typedInfiniteQueryOptions) expectTypeOf(data).toEqualTypeOf>() }) it('should resolve with InfiniteData of unknown when untyped', async () => { const queryClient = new QueryClient() - const data = await queryClient.infiniteQuery(untypedInfiniteQueryOptions) + const data = await infiniteQuery(queryClient, untypedInfiniteQueryOptions) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index bafb760ea7a..ae7145327ea 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -12,6 +12,7 @@ import { onlineManager, skipToken, } from '..' +import { infiniteQuery } from '../infiniteQuery' import { mockOnlineManagerIsOnline } from './utils' import type { InfiniteData, @@ -580,7 +581,7 @@ describe('queryClient', () => { pageParams: [0], }) await expect( - queryClient.infiniteQuery({ + infiniteQuery(queryClient, { queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -598,7 +599,7 @@ describe('queryClient', () => { ) await expect( - queryClient.infiniteQuery({ + infiniteQuery(queryClient, { queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -1093,24 +1094,21 @@ describe('queryClient', () => { Promise.resolve(data.pages[0]) await expect( - queryClient.infiniteQuery< - StrictData, - any, - StrictData, - StrictQueryKey, - number - >({ - queryKey: key, - queryFn: fetchFn, - getNextPageParam: () => undefined, - initialPageParam: 0, - }), + infiniteQuery( + queryClient, + { + queryKey: key, + queryFn: fetchFn, + getNextPageParam: () => undefined, + initialPageParam: 0, + }, + ), ).resolves.toStrictEqual(data) }) it('should return infinite query data', async () => { const key = createKey() - const result = await queryClient.infiniteQuery({ + const result = await infiniteQuery(queryClient, { queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, @@ -1134,7 +1132,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve(pageParam)) await expect( - queryClient.infiniteQuery({ + infiniteQuery(queryClient, { queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1160,7 +1158,7 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await queryClient.infiniteQuery({ + const result = await infiniteQuery(queryClient, { queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1181,7 +1179,7 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await queryClient.infiniteQuery({ + const result = await infiniteQuery(queryClient, { queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, @@ -1201,7 +1199,7 @@ describe('queryClient', () => { ) await expect( - queryClient.infiniteQuery({ + infiniteQuery(queryClient, { queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, @@ -1215,7 +1213,7 @@ describe('queryClient', () => { it('should throw when skipToken is provided with no cached data', async () => { await expect( - queryClient.infiniteQuery({ + infiniteQuery(queryClient, { queryKey: createKey(), queryFn: skipToken, getNextPageParam: () => undefined, @@ -1255,7 +1253,7 @@ describe('queryClient', () => { return query.state.data?.pages[0]?.staleTime ?? 0 } - const result = await queryClient.infiniteQuery({ + const result = await infiniteQuery(queryClient, { queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1278,7 +1276,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve({ value: `fetched-${String(pageParam)}` }), ) - const first = await queryClient.infiniteQuery({ + const first = await infiniteQuery(queryClient, { queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1296,7 +1294,7 @@ describe('queryClient', () => { refetchType: 'none', }) - const second = await queryClient.infiniteQuery({ + const second = await infiniteQuery(queryClient, { queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1310,7 +1308,7 @@ describe('queryClient', () => { it('should apply select to infinite query data', async () => { const key = createKey() - const result = await queryClient.infiniteQuery({ + const result = await infiniteQuery(queryClient, { queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, @@ -1330,14 +1328,15 @@ describe('queryClient', () => { const fetchFn: QueryFunction = () => Promise.resolve('data') - await queryClient - .infiniteQuery({ + await infiniteQuery( + queryClient, + { queryKey: key, queryFn: fetchFn, getNextPageParam: () => undefined, initialPageParam: 0, - }) - .catch(noop) + }, + ).catch(noop) const result = queryClient.getQueryData(key) @@ -1350,14 +1349,12 @@ describe('queryClient', () => { it('should return infinite query data', async () => { const key = createKey() - await queryClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => Number(pageParam), - getNextPageParam: () => undefined, - initialPageParam: 10, - }) - .catch(noop) + await infiniteQuery(queryClient, { + queryKey: key, + queryFn: ({ pageParam }) => Number(pageParam), + getNextPageParam: () => undefined, + initialPageParam: 10, + }).catch(noop) const result = queryClient.getQueryData(key) @@ -1370,16 +1367,14 @@ describe('queryClient', () => { it('should prefetch multiple pages', async () => { const key = createKey() - await queryClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => String(pageParam), - getNextPageParam: (_lastPage, _pages, lastPageParam) => - lastPageParam + 5, - initialPageParam: 10, - pages: 3, - }) - .catch(noop) + await infiniteQuery(queryClient, { + queryKey: key, + queryFn: ({ pageParam }) => String(pageParam), + getNextPageParam: (_lastPage, _pages, lastPageParam) => + lastPageParam + 5, + initialPageParam: 10, + pages: 3, + }).catch(noop) const result = queryClient.getQueryData(key) @@ -1393,18 +1388,16 @@ describe('queryClient', () => { const key = createKey() let count = 0 - await queryClient - .infiniteQuery({ - queryKey: key, - queryFn: ({ pageParam }) => String(pageParam), - getNextPageParam: (_lastPage, _pages, lastPageParam) => { - count++ - return lastPageParam >= 20 ? undefined : lastPageParam + 5 - }, - initialPageParam: 10, - pages: 5, - }) - .catch(noop) + await infiniteQuery(queryClient, { + queryKey: key, + queryFn: ({ pageParam }) => String(pageParam), + getNextPageParam: (_lastPage, _pages, lastPageParam) => { + count++ + return lastPageParam >= 20 ? undefined : lastPageParam + 5 + }, + initialPageParam: 10, + pages: 5, + }).catch(noop) const result = queryClient.getQueryData(key) diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index 49b24a8ed1b..a314182683b 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -1,3 +1,4 @@ +import { withInfiniteQueryBehavior } from './infiniteQueryBehavior' import { Mutation } from './mutation' import { noop } from './utils' import type { MutationState } from './mutation' @@ -380,16 +381,18 @@ export function hydrate( } } else { // Restore query + const queryOptions = { + ...client.getDefaultOptions().hydrate?.queries, + ...options?.defaultOptions?.queries, + queryKey, + queryHash, + meta, + } query = queryCache.build( client, - { - ...client.getDefaultOptions().hydrate?.queries, - ...options?.defaultOptions?.queries, - queryKey, - queryHash, - meta, - _type: queryType, - }, + queryType === 'infinite' + ? withInfiniteQueryBehavior(queryOptions) + : queryOptions, // Reset fetch status to idle to avoid // query being stuck in fetching state upon hydration { diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 366633ac0c2..ea4ba8469b5 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -10,6 +10,7 @@ export { dehydrateQuery, hydrate, } from './hydration' +export { infiniteQuery } from './infiniteQuery' export { InfiniteQueryObserver } from './infiniteQueryObserver' export { MutationCache } from './mutationCache' export type { MutationCacheNotifyEvent } from './mutationCache' diff --git a/packages/query-core/src/infiniteQuery.ts b/packages/query-core/src/infiniteQuery.ts new file mode 100644 index 00000000000..ea7ed0ae34f --- /dev/null +++ b/packages/query-core/src/infiniteQuery.ts @@ -0,0 +1,57 @@ +import { withInfiniteQueryBehavior } from './infiniteQueryBehavior' +import type { QueryClient } from './queryClient' +import type { + DefaultError, + InfiniteData, + InfiniteQueryExecuteOptions, + QueryKey, +} from './types' + +/** + * Asynchronous method to fetch and cache an infinite query, resolving with an + * {@link InfiniteData} object or throwing with the error. + * + * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many + * pages to fetch. If you omit `pages`, the client fetches up to the number of cached + * pages, or one page if the cache has no pages. + * @param client - The client that owns the query cache and defaults. + * @param options - The query to fetch and the options that control which pages to fetch. + * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if + * provided. It rejects with the error from the fetch or from `select`. + * @example + * ```ts + * try { + * const data = await infiniteQuery(queryClient, { + * queryKey, + * queryFn, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * console.log(data.pages) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> { + return client.query(withInfiniteQueryBehavior(options) as any) +} diff --git a/packages/query-core/src/infiniteQueryBehavior.ts b/packages/query-core/src/infiniteQueryBehavior.ts index 35e6341370b..ca414222941 100644 --- a/packages/query-core/src/infiniteQueryBehavior.ts +++ b/packages/query-core/src/infiniteQueryBehavior.ts @@ -15,122 +15,128 @@ import type { import type { FetchSignalContext } from './utils' /** - * Creates the behavior that fetches the pages of an infinite query: the next or previous page for - * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch. - * @param pages - The number of pages to fetch from the start when all pages are fetched again, - * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached - * pages. - * @returns The query behavior to set on an infinite query. + * Supplies the pagination behavior to the cache entry without changing the caller's options. + * @param options - The caller's query configuration, including page parameters. + * @returns A copy with pagination behavior attached. */ -export function infiniteQueryBehavior( - pages?: number, -): QueryBehavior> { - return { - onFetch: (context, query) => { - const options = context.options as InfiniteQueryPageParamsOptions - const direction = context.fetchOptions?.meta?.fetchMore?.direction - const oldPages = context.state.data?.pages || [] - const oldPageParams = context.state.data?.pageParams || [] - let result: InfiniteData = { pages: [], pageParams: [] } - let currentPage = 0 - - const fetchFn = async () => { - let cancelled = false - const signalContext: FetchSignalContext = context - const addSignalProperty = (object: object) => { - addConsumeAwareSignal( - object, - () => context.signal, - () => (cancelled = true), - signalContext[fetchSignal], - ) - } +export function withInfiniteQueryBehavior( + options: TOptions, +) { + return { ...options, _infiniteBehavior: infiniteBehavior } +} - const queryFn = ensureQueryFn(context.options, context.fetchOptions) +export const infiniteBehavior: QueryBehavior< + any, + any, + InfiniteData +> = { + onFetch: (context, query) => { + const options = + context.options as InfiniteQueryPageParamsOptions & { + pages?: number + } + const direction = context.fetchOptions?.meta?.fetchMore?.direction + const oldPages = context.state.data?.pages || [] + const oldPageParams = context.state.data?.pageParams || [] + let result: InfiniteData = { pages: [], pageParams: [] } + let currentPage = 0 + + const fetchFn = async () => { + let cancelled = false + const signalContext: FetchSignalContext = context + const addSignalProperty = (object: object) => { + addConsumeAwareSignal( + object, + () => context.signal, + () => (cancelled = true), + signalContext[fetchSignal], + ) + } - // Create function to fetch a page - const fetchPage = async ( - data: InfiniteData, - param: unknown, - previous?: boolean, - ): Promise> => { - if (cancelled) { - return Promise.reject(context.signal.reason) - } + const queryFn = ensureQueryFn(context.options, context.fetchOptions) - if (param == null && data.pages.length) { - return Promise.resolve(data) - } + // Create function to fetch a page + const fetchPage = async ( + data: InfiniteData, + param: unknown, + previous?: boolean, + ): Promise> => { + if (cancelled) { + return Promise.reject(context.signal.reason) + } - const queryFnContext = { - client: context.client, - queryKey: context.queryKey, - pageParam: param, - meta: context.options.meta, - } as QueryFunctionContext - addSignalProperty(queryFnContext) + if (param == null && data.pages.length) { + return Promise.resolve(data) + } - const page = await queryFn(queryFnContext) + const queryFnContext = { + client: context.client, + queryKey: context.queryKey, + pageParam: param, + meta: context.options.meta, + } as QueryFunctionContext + addSignalProperty(queryFnContext) - const { maxPages } = context.options - const addTo = previous ? addToStart : addToEnd + const page = await queryFn(queryFnContext) - return { - pages: addTo(data.pages, page, maxPages), - pageParams: addTo(data.pageParams, param, maxPages), - } - } + const { maxPages } = context.options + const addTo = previous ? addToStart : addToEnd - // fetch next / previous page? - if (direction && oldPages.length) { - const previous = direction === 'backward' - const pageParamFn = previous ? getPreviousPageParam : getNextPageParam - const oldData = { - pages: oldPages, - pageParams: oldPageParams, - } - const param = pageParamFn(options, oldData) - - result = await fetchPage(oldData, param, previous) - } else { - const remainingPages = pages ?? oldPages.length - - // Fetch all pages - do { - const param = - currentPage === 0 - ? oldPageParams[0] === undefined - ? options.initialPageParam - : oldPageParams[0] - : getNextPageParam(options, result) - if (currentPage > 0 && param == null) { - break - } - result = await fetchPage(result, param) - currentPage++ - } while (currentPage < remainingPages) + return { + pages: addTo(data.pages, page, maxPages), + pageParams: addTo(data.pageParams, param, maxPages), } - - return result } - if (context.options.persister) { - context.fetchFn = () => { - return context.options.persister?.( - fetchFn as any, - { - client: context.client, - queryKey: context.queryKey, - meta: context.options.meta, - signal: context.signal, - }, - query, - ) + + // fetch next / previous page? + if (direction && oldPages.length) { + const previous = direction === 'backward' + const pageParamFn = previous ? getPreviousPageParam : getNextPageParam + const oldData = { + pages: oldPages, + pageParams: oldPageParams, } + const param = pageParamFn(options, oldData) + + result = await fetchPage(oldData, param, previous) } else { - context.fetchFn = fetchFn + const remainingPages = options.pages ?? oldPages.length + + // Fetch all pages + do { + const param = + currentPage === 0 + ? oldPageParams[0] === undefined + ? options.initialPageParam + : oldPageParams[0] + : getNextPageParam(options, result) + if (currentPage > 0 && param == null) { + break + } + result = await fetchPage(result, param) + currentPage++ + } while (currentPage < remainingPages) + } + + return result + } + if (context.options.persister) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) } - }, - } + } else { + context.fetchFn = fetchFn + } + }, } /** diff --git a/packages/query-core/src/infiniteQueryObserver.ts b/packages/query-core/src/infiniteQueryObserver.ts index 9ec335050ca..e5d5d72599f 100644 --- a/packages/query-core/src/infiniteQueryObserver.ts +++ b/packages/query-core/src/infiniteQueryObserver.ts @@ -1,4 +1,8 @@ -import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' +import { + hasNextPage, + hasPreviousPage, + withInfiniteQueryBehavior, +} from './infiniteQueryBehavior' import { QueryObserver } from './queryObserver' import type { Query } from './query' import type { QueryClient } from './queryClient' @@ -119,8 +123,7 @@ export class InfiniteQueryObserver< TPageParam >, ): void { - options._type = 'infinite' - super.setOptions(options) + super.setOptions(withInfiniteQueryBehavior(options)) } /** @@ -137,10 +140,9 @@ export class InfiniteQueryObserver< TPageParam >, ): QueryObserverResultReader> { - return super.createResultReader({ - ...options, - _type: 'infinite', - }) as QueryObserverResultReader> + return super.createResultReader( + withInfiniteQueryBehavior(options), + ) as QueryObserverResultReader> } /** diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 29abb9d71c0..eab83de1afe 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -1,4 +1,3 @@ -import { infiniteQueryBehavior } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' import { Removable } from './removable' import { CancelledError, canFetch, createRetryer } from './retryer' @@ -290,7 +289,7 @@ export class Query< queryHash: string options!: QueryOptions state: QueryState - #queryType?: 'infinite' + #infiniteBehavior?: QueryBehavior #initialState: QueryState #revertState?: QueryState @@ -328,10 +327,10 @@ export class Query< /** * `'infinite'` for an infinite query, otherwise `undefined`. * @internal - * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). + * @returns The type of the query, derived from the installed fetch behavior. */ get queryType() { - return this.#queryType + return this.#infiniteBehavior ? ('infinite' as const) : undefined } /** @@ -354,8 +353,8 @@ export class Query< ): void { this.options = { ...this.#defaultOptions, ...options } - if (options?._type) { - this.#queryType = options._type + if (options?._infiniteBehavior) { + this.#infiniteBehavior = options._infiniteBehavior } this.updateGcTime(this.options.gcTime) @@ -802,12 +801,7 @@ export class Query< } as FetchContext addSignalProperty(context) - const behavior = - this.#queryType === 'infinite' - ? (infiniteQueryBehavior( - (this.options as { pages?: number }).pages, - ) as QueryBehavior) - : this.options.behavior + const behavior = this.#infiniteBehavior ?? this.options.behavior behavior?.onFetch(context, this as unknown as Query) // Store state in case the current fetch needs to be reverted diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 316aef6568b..6fb442924c0 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -20,8 +20,6 @@ import type { DefaultedQueryObserverOptions, InferDataFromTag, InferErrorFromTag, - InfiniteData, - InfiniteQueryExecuteOptions, InvalidateOptions, InvalidateQueryFilters, MutationKey, @@ -595,54 +593,6 @@ export class QueryClient { return queryData as unknown as TData } - /** - * Asynchronous method to fetch and cache an infinite query, resolving with an - * {@link InfiniteData} object or throwing with the error. - * - * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many - * pages to fetch. If you omit `pages`, the client fetches up to the number of cached - * pages, or one page if the cache has no pages. - * @param options - The query to fetch and the options that control which pages to fetch. - * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if - * provided. It rejects with the error from the fetch or from `select`. - * @example - * ```ts - * try { - * const data = await queryClient.infiniteQuery({ - * queryKey, - * queryFn, - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextCursor, - * }) - * console.log(data.pages) - * } catch (error) { - * console.log(error) - * } - * ``` - */ - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > { - options._type = 'infinite' - return this.query(options as any) - } - /** * Resumes mutations that were paused because there was no network connection. Does nothing * (resolving immediately) if the client is currently offline. diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index be9100f6049..10c672d455f 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -442,7 +442,7 @@ export interface QueryOptions< /** @internal */ _defaulted?: boolean /** @internal */ - _type?: 'infinite' + _infiniteBehavior?: QueryBehavior /** * Additional payload to be stored on each query. * Use this property to pass information that can be used in other places. @@ -752,7 +752,7 @@ type InfiniteQueryFetchPageOptions = Pick< } /** - * The options of `queryClient.infiniteQuery`. Extends {@link QueryExecuteOptions} + * The options of `infiniteQuery(queryClient, options)`. Extends {@link QueryExecuteOptions} * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. */ export type InfiniteQueryExecuteOptions< diff --git a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx index ea53c9c5406..5892d360ac2 100644 --- a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + dataTagSymbol, + infiniteQuery, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { infiniteQueryOptions } from '../infiniteQueryOptions' @@ -113,7 +118,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -127,7 +132,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -141,7 +146,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -154,7 +159,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/react-query/src/__tests__/ssr.test.tsx b/packages/react-query/src/__tests__/ssr.test.tsx index 8bd86910673..3e059f3865c 100644 --- a/packages/react-query/src/__tests__/ssr.test.tsx +++ b/packages/react-query/src/__tests__/ssr.test.tsx @@ -1,3 +1,4 @@ +import { infiniteQuery } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import * as React from 'react' import { renderToString } from 'react-dom/server' @@ -175,14 +176,12 @@ describe('Server Side Rendering', () => { ) } - void queryClient - .infiniteQuery({ - queryKey: key, - queryFn, - getNextPageParam: () => undefined, - initialPageParam: 0, - }) - .catch(noop) + void infiniteQuery(queryClient, { + queryKey: key, + queryFn, + getNextPageParam: () => undefined, + initialPageParam: 0, + }).catch(noop) await vi.advanceTimersByTimeAsync(10) const markup = renderToString( diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx index 82eaaaf3a0e..821dbb180ed 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + infiniteQuery as fetchInfiniteQuery, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { useInfiniteQuery } from '../useInfiniteQuery' @@ -19,7 +22,7 @@ describe('pageParam', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - queryClient.infiniteQuery({ + fetchInfiniteQuery(queryClient, { queryKey: ['key'], queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx index 7ca8f841e6f..ce6a0d9750e 100644 --- a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx @@ -1,3 +1,4 @@ +import { infiniteQuery } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' @@ -113,7 +114,7 @@ describe('usePrefetchInfiniteQuery', () => { allPages.length < data.length ? allPages.length : undefined, } - void queryClient.infiniteQuery({ ...queryOpts, pages: 3 }).catch(noop) + void infiniteQuery(queryClient, { ...queryOpts, pages: 3 }).catch(noop) await vi.advanceTimersByTimeAsync(30) queryOpts.queryFn.mockClear() diff --git a/packages/react-query/src/infiniteQueryOptions.ts b/packages/react-query/src/infiniteQueryOptions.ts index 93a4bdbb210..e302c95e2bd 100644 --- a/packages/react-query/src/infiniteQueryOptions.ts +++ b/packages/react-query/src/infiniteQueryOptions.ts @@ -126,7 +126,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. @@ -188,7 +188,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -247,7 +247,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/packages/react-query/src/types.ts b/packages/react-query/src/types.ts index 09e0a6b822e..220d51ca17c 100644 --- a/packages/react-query/src/types.ts +++ b/packages/react-query/src/types.ts @@ -103,7 +103,7 @@ export type UsePrefetchQueryOptions< } /** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(queryClient, options)`, * except `queryFn` is required unless a default query function has been defined. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. diff --git a/packages/react-query/src/useInfiniteQuery.ts b/packages/react-query/src/useInfiniteQuery.ts index 3fd5fb40d4b..6b5c136ad7e 100644 --- a/packages/react-query/src/useInfiniteQuery.ts +++ b/packages/react-query/src/useInfiniteQuery.ts @@ -33,7 +33,7 @@ import type { * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * ```tsx * import { useInfiniteQuery } from '@tanstack/react-query' @@ -90,7 +90,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx @@ -213,7 +213,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx diff --git a/packages/react-query/src/usePrefetchInfiniteQuery.tsx b/packages/react-query/src/usePrefetchInfiniteQuery.tsx index 7fbb28188a1..cca9b204c03 100644 --- a/packages/react-query/src/usePrefetchInfiniteQuery.tsx +++ b/packages/react-query/src/usePrefetchInfiniteQuery.tsx @@ -1,4 +1,4 @@ -import { noop } from '@tanstack/query-core' +import { infiniteQuery, noop } from '@tanstack/query-core' import { useQueryClient } from './QueryClientProvider' import type { DefaultError, @@ -11,7 +11,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' /** * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass - * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(queryClient, options)`, though * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless * a default query function has been defined. * @@ -22,7 +22,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's * already there or already in flight. - * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(queryClient, options)`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. * @example @@ -68,6 +68,6 @@ export function usePrefetchInfiniteQuery< const client = useQueryClient(queryClient) if (!client.getQueryState(options.queryKey)) { - void client.infiniteQuery(options).catch(noop) + void infiniteQuery(client, options).catch(noop) } } diff --git a/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx index 587903775c4..7d99891fcc1 100644 --- a/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + dataTagSymbol, + infiniteQuery, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { infiniteQueryOptions } from '../infiniteQueryOptions' @@ -27,7 +32,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 0, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -41,7 +46,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -55,7 +60,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -68,7 +73,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 0, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/solid-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/solid-query/src/__tests__/useInfiniteQuery.test-d.tsx index 365315eade5..c3b276d972c 100644 --- a/packages/solid-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/solid-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,3 +1,4 @@ +import { infiniteQuery as fetchInfiniteQuery } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../QueryClient' @@ -19,7 +20,7 @@ describe('useInfiniteQuery', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - queryClient.infiniteQuery({ + fetchInfiniteQuery(queryClient, { queryKey: createKey(), queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/solid-query/src/infiniteQueryOptions.ts b/packages/solid-query/src/infiniteQueryOptions.ts index acce015b55d..d2886325bab 100644 --- a/packages/solid-query/src/infiniteQueryOptions.ts +++ b/packages/solid-query/src/infiniteQueryOptions.ts @@ -66,7 +66,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. @@ -133,7 +133,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/packages/solid-query/src/useInfiniteQuery.ts b/packages/solid-query/src/useInfiniteQuery.ts index 5af32141142..092d0a828cb 100644 --- a/packages/solid-query/src/useInfiniteQuery.ts +++ b/packages/solid-query/src/useInfiniteQuery.ts @@ -35,7 +35,7 @@ import type { * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * ```tsx * import { For } from 'solid-js' @@ -96,7 +96,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx diff --git a/packages/svelte-query/src/createInfiniteQuery.ts b/packages/svelte-query/src/createInfiniteQuery.ts index dc07c631dd1..55b0fc3d5a1 100644 --- a/packages/svelte-query/src/createInfiniteQuery.ts +++ b/packages/svelte-query/src/createInfiniteQuery.ts @@ -31,7 +31,7 @@ import type { * @returns The current query result, plus `fetchNextPage`/`fetchPreviousPage`/`hasNextPage`/`hasPreviousPage` * to page through the query. * @see {@link infiniteQueryOptions} to share these options between `createInfiniteQuery` and imperative APIs - * like `queryClient.infiniteQuery`. + * like `infiniteQuery(queryClient, options)`. */ export function createInfiniteQuery< TQueryFnData = unknown, @@ -65,7 +65,7 @@ export function createInfiniteQuery< * @returns The current query result, plus `fetchNextPage`/`fetchPreviousPage`/`hasNextPage`/`hasPreviousPage` * to page through the query. * @see {@link infiniteQueryOptions} to share these options between `createInfiniteQuery` and imperative APIs - * like `queryClient.infiniteQuery`. + * like `infiniteQuery(queryClient, options)`. */ export function createInfiniteQuery< TQueryFnData = unknown, @@ -96,7 +96,7 @@ export function createInfiniteQuery< * @returns The current query result, plus `fetchNextPage`/`fetchPreviousPage`/`hasNextPage`/`hasPreviousPage` * to page through the query. * @see {@link infiniteQueryOptions} to share these options between `createInfiniteQuery` and imperative APIs - * like `queryClient.infiniteQuery`. + * like `infiniteQuery(queryClient, options)`. * @example * Fetching the next page from a "Load More" button click: * ```svelte diff --git a/packages/svelte-query/src/infiniteQueryOptions.ts b/packages/svelte-query/src/infiniteQueryOptions.ts index c9c2fb03fc3..bf57bbcfef1 100644 --- a/packages/svelte-query/src/infiniteQueryOptions.ts +++ b/packages/svelte-query/src/infiniteQueryOptions.ts @@ -59,7 +59,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`. * These options can be shared across `createInfiniteQuery` calls and imperative APIs such as - * `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for. + * `infiniteQuery(queryClient, options)`. `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to @@ -122,7 +122,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `createInfiniteQuery`. * These options can be shared across `createInfiniteQuery` calls and imperative APIs such as - * `queryClient.infiniteQuery`. `options.queryKey` is required and is the query key to generate options for. + * `infiniteQuery(queryClient, options)`. `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to * `createInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/packages/svelte-query/tests/createInfiniteQuery/createInfiniteQuery.test-d.ts b/packages/svelte-query/tests/createInfiniteQuery/createInfiniteQuery.test-d.ts index c2c996f5021..82b78192ff2 100644 --- a/packages/svelte-query/tests/createInfiniteQuery/createInfiniteQuery.test-d.ts +++ b/packages/svelte-query/tests/createInfiniteQuery/createInfiniteQuery.test-d.ts @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + infiniteQuery as fetchInfiniteQuery, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { createInfiniteQuery, infiniteQueryOptions } from '../../src/index.js' @@ -19,7 +22,7 @@ describe('createInfiniteQuery', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - queryClient.infiniteQuery({ + fetchInfiniteQuery(queryClient, { queryKey: createKey(), queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts b/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts index 956544d9602..c8797facaa4 100644 --- a/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts +++ b/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts @@ -1,4 +1,4 @@ -import { QueryClient, skipToken } from '@tanstack/query-core' +import { QueryClient, infiniteQuery, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { createInfiniteQuery, infiniteQueryOptions } from '../src/index.js' @@ -74,7 +74,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -88,7 +88,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -102,7 +102,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) @@ -115,7 +115,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await infiniteQuery(new QueryClient(), options) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/vue-query/src/__tests__/infiniteQueryOptions.test-d.ts b/packages/vue-query/src/__tests__/infiniteQueryOptions.test-d.ts index 93c2240f62c..ede9fc052eb 100644 --- a/packages/vue-query/src/__tests__/infiniteQueryOptions.test-d.ts +++ b/packages/vue-query/src/__tests__/infiniteQueryOptions.test-d.ts @@ -3,7 +3,7 @@ import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { reactive } from 'vue' import { infiniteQueryOptions } from '../infiniteQueryOptions' -import { QueryClient } from '../queryClient' +import { QueryClient, infiniteQuery } from '../queryClient' import { useInfiniteQuery } from '../useInfiniteQuery' import type { InfiniteData } from '@tanstack/query-core' @@ -116,7 +116,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery({ + const data = await infiniteQuery(new QueryClient(), { ...options, staleTime: 0, pages: 1, @@ -134,7 +134,7 @@ describe('infiniteQueryOptions', () => { select: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery({ + const data = await infiniteQuery(new QueryClient(), { ...options, staleTime: 0, pages: 1, diff --git a/packages/vue-query/src/__tests__/queryClient.test-d.ts b/packages/vue-query/src/__tests__/queryClient.test-d.ts index f5322e19842..08ed31ea955 100644 --- a/packages/vue-query/src/__tests__/queryClient.test-d.ts +++ b/packages/vue-query/src/__tests__/queryClient.test-d.ts @@ -1,6 +1,6 @@ import { assertType, describe, expectTypeOf, it } from 'vitest' import { ref } from 'vue' -import { QueryClient } from '../queryClient' +import { QueryClient, infiniteQuery } from '../queryClient' import type { DataTag, InfiniteData, QueryState } from '@tanstack/query-core' describe('getQueryData', () => { @@ -190,7 +190,7 @@ describe('query', () => { describe('infiniteQuery', () => { it('should return infinite data', async () => { - const data = await new QueryClient().infiniteQuery({ + const data = await infiniteQuery(new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, @@ -201,7 +201,7 @@ describe('infiniteQuery', () => { }) it('should return the selected type', () => { - const result = new QueryClient().infiniteQuery({ + const result = infiniteQuery(new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), getNextPageParam: () => 2, @@ -213,7 +213,8 @@ describe('infiniteQuery', () => { }) it('should not accept top-level options getters', () => { - assertType>([ + assertType>([ + new QueryClient(), // @ts-expect-error One-shot imperative methods do not resolve top-level getters () => ({ queryKey: ['key'], @@ -225,7 +226,8 @@ describe('infiniteQuery', () => { }) it('should allow passing pages with getNextPageParam', () => { - assertType>([ + assertType>([ + new QueryClient(), { queryKey: ['key'], queryFn: () => Promise.resolve('string'), @@ -237,7 +239,8 @@ describe('infiniteQuery', () => { }) it('should not allow passing pages without getNextPageParam', () => { - assertType>([ + assertType>([ + new QueryClient(), // @ts-expect-error Property 'getNextPageParam' is missing { queryKey: ['key'], @@ -249,7 +252,7 @@ describe('infiniteQuery', () => { }) it('should preserve page param inference', () => { - new QueryClient().infiniteQuery({ + infiniteQuery(new QueryClient(), { queryKey: ['key'], queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/vue-query/src/__tests__/queryClient.test.ts b/packages/vue-query/src/__tests__/queryClient.test.ts index c8dc8c94f79..4daf7bc44de 100644 --- a/packages/vue-query/src/__tests__/queryClient.test.ts +++ b/packages/vue-query/src/__tests__/queryClient.test.ts @@ -4,7 +4,7 @@ import { ref, unref } from 'vue' import { infiniteQueryOptions } from '../infiniteQueryOptions' import { MutationCache } from '../mutationCache' import { QueryCache } from '../queryCache' -import { QueryClient } from '../queryClient' +import { QueryClient, infiniteQuery } from '../queryClient' import { queryOptions } from '../queryOptions' // Get the prototype methods dynamically @@ -385,12 +385,13 @@ describe('QueryCache', () => { }) describe('infiniteQuery', () => { - it('should properly unwrap queryKey, initialPageParam, pages, and select', () => { + it('should properly unwrap queryKey, initialPageParam, pages, and select', async () => { const queryClient = new QueryClient() const getNextPageParam = () => 1 const select = (data: { pages: Array }) => data.pages.length - queryClient.infiniteQuery({ + await infiniteQuery(queryClient, { + queryFn: () => Promise.resolve('item'), queryKey: queryKeyRef, initialPageParam: ref(0), pages: ref(2), @@ -398,7 +399,7 @@ describe('QueryCache', () => { select: ref(select), }) - expect(QueryClientOrigin.prototype.infiniteQuery).toHaveBeenCalledWith( + expect(QueryClientOrigin.prototype.query).toHaveBeenCalledWith( expect.objectContaining({ queryKey: queryKeyUnref, initialPageParam: 0, @@ -409,7 +410,7 @@ describe('QueryCache', () => { ) }) - it('should properly unwrap getNextPageParam when using infiniteQueryOptions', () => { + it('should properly unwrap getNextPageParam when using infiniteQueryOptions', async () => { const queryClient = new QueryClient() const getNextPageParam = () => 12 @@ -419,13 +420,14 @@ describe('QueryCache', () => { getNextPageParam: ref(getNextPageParam), }) - queryClient.infiniteQuery({ + await infiniteQuery(queryClient, { + queryFn: () => Promise.resolve('item'), ...unref(options), staleTime: 0, pages: 1, }) - expect(QueryClientOrigin.prototype.infiniteQuery).toHaveBeenCalledWith( + expect(QueryClientOrigin.prototype.query).toHaveBeenCalledWith( expect.objectContaining({ queryKey: queryKeyUnref, initialPageParam: 0, diff --git a/packages/vue-query/src/__tests__/usePrefetchInfiniteQuery.test.ts b/packages/vue-query/src/__tests__/usePrefetchInfiniteQuery.test.ts index 2c4f2a500c6..e2109df3c5b 100644 --- a/packages/vue-query/src/__tests__/usePrefetchInfiniteQuery.test.ts +++ b/packages/vue-query/src/__tests__/usePrefetchInfiniteQuery.test.ts @@ -15,7 +15,7 @@ describe('usePrefetchInfiniteQuery', () => { it('should prefetch infinite query if query state does not exist', () => { const queryClient = new QueryClient() - const infiniteQuerySpy = vi.spyOn(queryClient, 'infiniteQuery') + const querySpy = vi.spyOn(queryClient, 'query') const queryFn = () => Promise.resolve({ data: 'prefetched', currentPage: 1 }) const getNextPageParam = () => undefined @@ -32,18 +32,20 @@ describe('usePrefetchInfiniteQuery', () => { queryClient, ) - expect(infiniteQuerySpy).toHaveBeenCalledTimes(1) - expect(infiniteQuerySpy).toHaveBeenCalledWith({ - queryKey: key, - queryFn, - initialPageParam: 1, - getNextPageParam, - }) + expect(querySpy).toHaveBeenCalledTimes(1) + expect(querySpy).toHaveBeenCalledWith( + expect.objectContaining({ + queryKey: key, + queryFn, + initialPageParam: 1, + getNextPageParam, + }), + ) }) it('should not prefetch infinite query if query state exists', () => { const queryClient = new QueryClient() - const infiniteQuerySpy = vi.spyOn(queryClient, 'infiniteQuery') + const querySpy = vi.spyOn(queryClient, 'query') const queryFn = () => Promise.resolve({ data: 'prefetched', currentPage: 1 }) @@ -63,12 +65,12 @@ describe('usePrefetchInfiniteQuery', () => { queryClient, ) - expect(infiniteQuerySpy).not.toHaveBeenCalled() + expect(querySpy).not.toHaveBeenCalled() }) it('should unwrap refs in infinite query options', () => { const queryClient = new QueryClient() - const infiniteQuerySpy = vi.spyOn(queryClient, 'infiniteQuery') + const querySpy = vi.spyOn(queryClient, 'query') const nestedRef = ref('value') const key = createKey() const queryFn = () => @@ -85,17 +87,19 @@ describe('usePrefetchInfiniteQuery', () => { queryClient, ) - expect(infiniteQuerySpy).toHaveBeenCalledWith({ - queryKey: [...key, 'value'], - queryFn, - initialPageParam: 1, - getNextPageParam, - }) + expect(querySpy).toHaveBeenCalledWith( + expect.objectContaining({ + queryKey: [...key, 'value'], + queryFn, + initialPageParam: 1, + getNextPageParam, + }), + ) }) it('should prefetch infinite query again when query key changes reactively', async () => { const queryClient = new QueryClient() - const infiniteQuerySpy = vi.spyOn(queryClient, 'infiniteQuery') + const querySpy = vi.spyOn(queryClient, 'query') const keyRef = ref('first') const key = createKey() const queryFn = () => @@ -112,23 +116,29 @@ describe('usePrefetchInfiniteQuery', () => { queryClient, ) - expect(infiniteQuerySpy).toHaveBeenCalledTimes(1) - expect(infiniteQuerySpy).toHaveBeenNthCalledWith(1, { - queryKey: [...key, 'first'], - queryFn, - initialPageParam: 1, - getNextPageParam, - }) + expect(querySpy).toHaveBeenCalledTimes(1) + expect(querySpy).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + queryKey: [...key, 'first'], + queryFn, + initialPageParam: 1, + getNextPageParam, + }), + ) keyRef.value = 'second' await nextTick() - expect(infiniteQuerySpy).toHaveBeenCalledTimes(2) - expect(infiniteQuerySpy).toHaveBeenNthCalledWith(2, { - queryKey: [...key, 'second'], - queryFn, - initialPageParam: 1, - getNextPageParam, - }) + expect(querySpy).toHaveBeenCalledTimes(2) + expect(querySpy).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + queryKey: [...key, 'second'], + queryFn, + initialPageParam: 1, + getNextPageParam, + }), + ) }) it('should warn when used outside of setup function in development mode', () => { diff --git a/packages/vue-query/src/index.ts b/packages/vue-query/src/index.ts index 67a1008284b..57b99bbb3d0 100644 --- a/packages/vue-query/src/index.ts +++ b/packages/vue-query/src/index.ts @@ -4,7 +4,7 @@ export * from '@tanstack/query-core' export { useQueryClient } from './useQueryClient' export { VueQueryPlugin } from './vueQueryPlugin' -export { QueryClient } from './queryClient' +export { QueryClient, infiniteQuery } from './queryClient' export { QueryCache } from './queryCache' export { queryOptions } from './queryOptions' export type { diff --git a/packages/vue-query/src/infiniteQueryOptions.ts b/packages/vue-query/src/infiniteQueryOptions.ts index d1a76b5c921..83fe68065e8 100644 --- a/packages/vue-query/src/infiniteQueryOptions.ts +++ b/packages/vue-query/src/infiniteQueryOptions.ts @@ -77,7 +77,7 @@ export type DefinedInitialDataInfiniteOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never @@ -130,7 +130,7 @@ export function infiniteQueryOptions< /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(queryClient, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to * `useInfiniteQuery`. diff --git a/packages/vue-query/src/queryClient.ts b/packages/vue-query/src/queryClient.ts index acb3e1dd355..90e35436136 100644 --- a/packages/vue-query/src/queryClient.ts +++ b/packages/vue-query/src/queryClient.ts @@ -1,4 +1,7 @@ -import { QueryClient as QC } from '@tanstack/query-core' +import { + QueryClient as QC, + infiniteQuery as coreInfiniteQuery, +} from '@tanstack/query-core' import { nextTick, ref } from 'vue' import { MutationCache } from './mutationCache' import { QueryCache } from './queryCache' @@ -328,73 +331,6 @@ export class QueryClient extends QC { ) } - // These one-shot imperative methods do not resolve top-level option getters. - // Resolve getters explicitly before calling, e.g. queryClient.infiniteQuery(options()). - override infiniteQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - /** {@inheritDoc QueryClient.infiniteQuery:0} */ - override infiniteQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: MaybeRefDeep< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - override infiniteQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: MaybeRefDeep< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > { - return super.infiniteQuery(cloneDeepUnref(options)) - } - override setDefaultOptions(options: MaybeRefDeep): void { super.setDefaultOptions(cloneDeepUnref(options)) } @@ -442,3 +378,77 @@ export class QueryClient extends QC { return super.getMutationDefaults(cloneDeepUnref(mutationKey)) } } + +/** + * Fetches and caches an infinite query using the Vue client's defaults. + * Accepts refs in the options. Call top-level option getters before passing their result. + * @param client - The Vue query client. + * @param options - The query key, fetch function, and pagination settings. + * @returns The cached pages, or the selected result when `select` is provided. + */ +export function infiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> +export function infiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: MaybeRefDeep< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> +export function infiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + client: QueryClient, + options: MaybeRefDeep< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, +): Promise< + Array extends Array> + ? InfiniteData + : TData +> { + return coreInfiniteQuery(client, cloneDeepUnref(options)) +} diff --git a/packages/vue-query/src/usePrefetchInfiniteQuery.ts b/packages/vue-query/src/usePrefetchInfiniteQuery.ts index cff1d885319..fb579ad54e7 100644 --- a/packages/vue-query/src/usePrefetchInfiniteQuery.ts +++ b/packages/vue-query/src/usePrefetchInfiniteQuery.ts @@ -1,5 +1,6 @@ import { noop } from '@tanstack/query-core' import { getCurrentScope, unref, watchEffect } from 'vue' +import { infiniteQuery } from './queryClient' import { useQueryClient } from './useQueryClient' import { cloneDeepUnref } from './utils' import type { @@ -14,7 +15,7 @@ import type { QueryClient } from './queryClient' import type { MaybeRefDeep, MaybeRefOrGetter } from './types' /** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(queryClient, options)`, * except that `queryFn` can't be `skipToken`. */ export type UsePrefetchInfiniteQueryOptions< @@ -57,7 +58,7 @@ function isGetter(value: MaybeRefOrGetter): value is () => T { /** * `usePrefetchInfiniteQuery` does not return anything — it fires a prefetch as a reactive side effect, useful * for kicking off a fetch ahead of the component that will actually render the data with `useInfiniteQuery`. - * You can pass everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, + * You can pass everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(queryClient, options)`, * though `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required * unless a default query function has been defined. * @@ -72,7 +73,7 @@ function isGetter(value: MaybeRefOrGetter): value is () => T { * Fire this during render, before a suspense boundary that wraps a component using `useInfiniteQuery`'s * `suspense()` — see the {@link https://tanstack.com/query/latest/docs/framework/vue/guides/suspense | Suspense guide}. * @param options - A `ref`, plain value, or reactive getter resolving to the - * {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(queryClient, options)`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` * will be used. * @example @@ -139,7 +140,7 @@ export function usePrefetchInfiniteQuery< > = cloneDeepUnref(resolvedOptions) if (!client.getQueryState(clonedOptions.queryKey)) { - void client.infiniteQuery(clonedOptions).then(noop).catch(noop) + void infiniteQuery(client, clonedOptions).then(noop).catch(noop) } }) }