Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cold-islands-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/vue-query': minor
---

add new imperitive methods to QueryClient proxy
5 changes: 5 additions & 0 deletions .changeset/true-cameras-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-core': minor
---

add query and infiniteQuery methods, deprecate old imperative methods
36 changes: 23 additions & 13 deletions docs/framework/vue/guides/prefetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,30 @@ 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, you can use the `prefetchQuery` method to prefetch the results of a query to be placed into the cache:
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:

[//]: # 'ExamplePrefetching'

```tsx
import { noop } from '@tanstack/vue-query'

const prefetchTodos = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
await queryClient
.query({
queryKey: ['todos'],
queryFn: fetchTodos,
})
.catch(noop)
}
```

[//]: # 'ExamplePrefetching'

- If **fresh** data for this query is already in the cache, the data will not be fetched
- If a `staleTime` is passed eg. `prefetchQuery({ queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified `staleTime`, the query will be fetched
- If a `staleTime` is passed e.g. `queryClient.query({ queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified `staleTime`, the query will be fetched
- As `useQuery` will retry fetches and handle errors, you can use `void` to ignore the promise from `query` and `.catch(noop)` to ignore errors.
- If you want to always return cached data when it exists, use `staleTime: 'static'`
- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `gcTime`.

## Prefetching Infinite Queries
Expand All @@ -30,15 +36,19 @@ Infinite Queries can be prefetched like regular Queries. Per default, only the f
[//]: # 'ExampleInfiniteQuery'

```tsx
import { noop } from '@tanstack/vue-query'

const prefetchProjects = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchInfiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
pages: 3, // prefetch the first 3 pages
})
await queryClient
.infiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
pages: 3, // prefetch the first 3 pages
})
.catch(noop)
}
```

Expand Down
11 changes: 6 additions & 5 deletions docs/framework/vue/guides/ssr.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,13 @@ 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.prefetchQuery` or `suspense`
- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense`

```ts
export default defineComponent({
setup() {
const { data, suspense } = useQuery({
const queryClient = useQueryClient()
const { data } = useQuery({
queryKey: ['test'],
queryFn: fetcher,
})
Expand Down Expand Up @@ -110,7 +111,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.prefetchQuery` or `suspense`
- Prefetch all the queries that you need with `queryClient.query`, `queryClient.infiniteQuery`, or `suspense`
- Dehydrate `queryClient` to the `nuxtContext`

```vue
Expand Down Expand Up @@ -169,7 +170,7 @@ export default defineComponent({
</script>
```

As demonstrated, it's fine to prefetch some queries and let others fetch on the queryClient. This means you can control what content server renders or not by adding or removing `prefetchQuery` or `suspense` for a specific query.
As demonstrated, it's fine to prefetch some queries and let others fetch on the client. This means you can control what content server renders or not by adding or removing `queryClient.query` or `suspense` for a specific query.

## Using Vite SSR

Expand Down Expand Up @@ -237,7 +238,7 @@ Then, call VueQuery from any component using Vue's `onServerPrefetch`:

Any query with an error is automatically excluded from dehydration. This means that the default behavior is to pretend these queries were never loaded on the server, usually showing a loading state instead, and retrying the queries on the queryClient. This happens regardless of error.

Sometimes this behavior is not desirable, maybe you want to render an error page with a correct status code instead on certain errors or queries. In those cases, use `fetchQuery` and catch any errors to handle those manually.
Sometimes this behavior is not desirable, maybe you want to render an error page with a correct status code instead on certain errors or queries. In those cases, use `queryClient.query` and catch any errors to handle those manually.

### Staleness is measured from when the query was fetched on the server

Expand Down
176 changes: 171 additions & 5 deletions packages/query-core/src/__tests__/queryClient.test-d.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { assertType, describe, expectTypeOf, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import { QueryClient } from '../queryClient'
import { skipToken } from '../utils'
import type { MutationFilters, QueryFilters, Updater } from '../utils'
import type { Mutation } from '../mutation'
import type { Query, QueryState } from '../query'
Expand All @@ -11,6 +12,7 @@ import type {
EnsureQueryDataOptions,
FetchInfiniteQueryOptions,
InfiniteData,
InfiniteQueryExecuteOptions,
MutationOptions,
OmitKeyof,
QueryKey,
Expand Down Expand Up @@ -158,7 +160,38 @@ describe('getQueryState', () => {
})
})

describe('fetchQuery', () => {
it('should not allow passing select option', () => {
assertType<Parameters<QueryClient['fetchQuery']>>([
{
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
// @ts-expect-error `select` is not supported on fetchQuery options
select: (data: string) => data.length,
},
])
})
})

describe('fetchInfiniteQuery', () => {
it('should not allow passing select option', () => {
assertType<Parameters<QueryClient['fetchInfiniteQuery']>>([
{
queryKey: ['key'],
queryFn: () => Promise.resolve({ count: 1 }),
initialPageParam: 1,
getNextPageParam: () => 2,
// @ts-expect-error `select` is not supported on fetchInfiniteQuery options
select: (data) => ({
pages: data.pages.map(
(x: unknown) => `count: ${(x as { count: number }).count}`,
),
pageParams: data.pageParams,
}),
},
])
})

it('should allow passing pages', async () => {
const data = await new QueryClient().fetchInfiniteQuery({
queryKey: queryKey(),
Expand All @@ -171,7 +204,7 @@ describe('fetchInfiniteQuery', () => {
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
})

it('should not allow passing getNextPageParam without pages', () => {
it('should allow passing getNextPageParam without pages', () => {
assertType<Parameters<QueryClient['fetchInfiniteQuery']>>([
{
queryKey: ['key'],
Expand All @@ -195,6 +228,105 @@ describe('fetchInfiniteQuery', () => {
})
})

describe('query', () => {
it('should allow passing select option', () => {
const result = new QueryClient().query({
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
select: (data) => data.length,
})

expectTypeOf(result).toEqualTypeOf<Promise<number>>()
})

it('should infer select type with skipToken queryFn', () => {
const result = new QueryClient().query({
queryKey: ['key'],
queryFn: skipToken,
select: (data: string) => data.length,
})

expectTypeOf(result).toEqualTypeOf<Promise<number>>()
})

it('should infer select type with skipToken queryFn and enabled false', () => {
const result = new QueryClient().query({
queryKey: ['key'],
queryFn: skipToken,
enabled: false,
select: (data: string) => data.length,
})

expectTypeOf(result).toEqualTypeOf<Promise<number>>()
})

it('should infer select type with skipToken queryFn and enabled true', () => {
const result = new QueryClient().query({
queryKey: ['key'],
queryFn: skipToken,
enabled: true,
select: (data: string) => data.length,
})

expectTypeOf(result).toEqualTypeOf<Promise<number>>()
})
})

describe('infiniteQuery', () => {
it('should allow passing select option', () => {
const result = new QueryClient().infiniteQuery({
queryKey: ['key'],
queryFn: () => Promise.resolve({ count: 1 }),
initialPageParam: 1,
getNextPageParam: () => 2,
select: (data) => ({
pages: data.pages.map(
(x) => `count: ${(x as { count: number }).count}`,
),
}),
})

expectTypeOf(result).toEqualTypeOf<Promise<{ pages: Array<string> }>>()
})

it('should allow passing pages', async () => {
const result = await new QueryClient().infiniteQuery({
queryKey: ['key'],
queryFn: () => Promise.resolve({ count: 1 }),
getNextPageParam: () => 1,
initialPageParam: 1,
pages: 5,
})

expectTypeOf(result).toEqualTypeOf<
InfiniteData<{ count: number }, number>
>()
})

it('should allow passing getNextPageParam without pages', () => {
assertType<Parameters<QueryClient['infiniteQuery']>>([
{
queryKey: ['key'],
queryFn: () => Promise.resolve({ count: 1 }),
initialPageParam: 1,
getNextPageParam: () => 1,
},
])
})

it('should not allow passing pages without getNextPageParam', () => {
assertType<Parameters<QueryClient['infiniteQuery']>>([
// @ts-expect-error Property 'getNextPageParam' is missing
{
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
initialPageParam: 1,
pages: 5,
},
])
})
})

describe('defaultOptions', () => {
it('should have a typed QueryFunctionContext', () => {
new QueryClient({
Expand Down Expand Up @@ -228,19 +360,35 @@ describe('fully typed usage', () => {
// Construct typed arguments
//

const infiniteQueryOptions: InfiniteQueryExecuteOptions<
TData,
TError,
InfiniteData<TData>
> = {
queryKey: ['key', 'infinite'],
pages: 5,
getNextPageParam: (lastPage) => {
expectTypeOf(lastPage).toEqualTypeOf<TData>()
return 0
},
initialPageParam: 0,
}

const queryOptions: EnsureQueryDataOptions<TData, TError> = {
queryKey: ['key'] as any,
queryKey: ['key', 'query'],
}

const fetchInfiniteQueryOptions: FetchInfiniteQueryOptions<TData, TError> =
{
queryKey: ['key'] as any,
queryKey: ['key', 'infinite'],
pages: 5,
getNextPageParam: (lastPage) => {
expectTypeOf(lastPage).toEqualTypeOf<TData>()
return 0
},
initialPageParam: 0,
}

const mutationOptions: MutationOptions<TData, TError> = {}

const queryFilters: QueryFilters<DataTag<QueryKey, TData, TError>> = {
Expand Down Expand Up @@ -311,11 +459,19 @@ describe('fully typed usage', () => {
const fetchedQuery = await queryClient.fetchQuery(queryOptions)
expectTypeOf(fetchedQuery).toEqualTypeOf<TData>()

const queriedData = await queryClient.query(queryOptions)
expectTypeOf(queriedData).toEqualTypeOf<TData>()

queryClient.prefetchQuery(queryOptions)

const infiniteQuery = await queryClient.fetchInfiniteQuery(
const fetchInfiniteQueryResult = await queryClient.fetchInfiniteQuery(
fetchInfiniteQueryOptions,
)
expectTypeOf(fetchInfiniteQueryResult).toEqualTypeOf<
InfiniteData<TData, unknown>
>()

const infiniteQuery = await queryClient.infiniteQuery(infiniteQueryOptions)
expectTypeOf(infiniteQuery).toEqualTypeOf<InfiniteData<TData, unknown>>()

const infiniteQueryData = await queryClient.ensureInfiniteQueryData(
Expand Down Expand Up @@ -450,9 +606,19 @@ describe('fully typed usage', () => {
const fetchedQuery = await queryClient.fetchQuery(queryOptions)
expectTypeOf(fetchedQuery).toEqualTypeOf<unknown>()

const queriedData = await queryClient.query(queryOptions)
expectTypeOf(queriedData).toEqualTypeOf<unknown>()

queryClient.prefetchQuery(queryOptions)

const infiniteQuery = await queryClient.fetchInfiniteQuery(
const fetchInfiniteQueryResult = await queryClient.fetchInfiniteQuery(
fetchInfiniteQueryOptions,
)
expectTypeOf(fetchInfiniteQueryResult).toEqualTypeOf<
InfiniteData<unknown, unknown>
>()

const infiniteQuery = await queryClient.infiniteQuery(
fetchInfiniteQueryOptions,
)
expectTypeOf(infiniteQuery).toEqualTypeOf<InfiniteData<unknown, unknown>>()
Expand Down
Loading
Loading