Server: Phase 2 (REVIEW not respected yet)

This commit is contained in:
Thomas Karner committed 2026-09-21 11:24:43 +02:00
1 parent 5d16ded553
commit 142b47674d
4271 files changed
+1203269

No files matched your search

+171
View File
@@ -0,0 +1,171 @@
'use client'
import * as React from 'react'
import { hydrate } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type {
DehydratedState,
HydrateOptions,
OmitKeyof,
QueryClient,
} from '@tanstack/query-core'
/**
* The props accepted by `HydrationBoundary`.
*/
export interface HydrationBoundaryProps {
/**
* The state to hydrate.
*/
state: DehydratedState | null | undefined
/**
* Optional. Note: unlike `hydrate`, `mutations` cannot be set here.
*/
options?: OmitKeyof<HydrateOptions, 'defaultOptions'> & {
defaultOptions?: OmitKeyof<
Exclude<HydrateOptions['defaultOptions'], undefined>,
'mutations'
>
}
/**
* The components to render — always rendered unconditionally, not gated on hydration. New queries are
* hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated
* data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it
* lands.
*/
children?: React.ReactNode
/**
* Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used.
*/
queryClient?: QueryClient
}
/**
* `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by
* `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on
* update timestamp.
*
* Note: Only `queries` can be dehydrated with an `HydrationBoundary`.
*
* @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the
* cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect
* after commit.
*
* @example
* ```tsx
* import { HydrationBoundary } from '@tanstack/react-query'
*
* function App() {
* return <HydrationBoundary state={dehydratedState}>...</HydrationBoundary>
* }
* ```
*
* @example
* Server-side prefetch handed off to the client via `dehydrate`:
* ```tsx
* import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query'
*
* async function ServerComponent() {
* const queryClient = getQueryClient()
*
* await queryClient
* .query({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
* .catch(noop)
*
* return (
* <HydrationBoundary state={dehydrate(queryClient)}>
* <Posts />
* </HydrationBoundary>
* )
* }
* ```
*/
export const HydrationBoundary = ({
children,
options = {},
state,
queryClient,
}: HydrationBoundaryProps) => {
const client = useQueryClient(queryClient)
const optionsRef = React.useRef(options)
React.useEffect(() => {
optionsRef.current = options
})
// This useMemo is for performance reasons only, everything inside it must
// be safe to run in every render and code here should be read as "in render".
//
// This code needs to happen during the render phase, because after initial
// SSR, hydration needs to happen _before_ children render. Also, if hydrating
// during a transition, we want to hydrate as much as is safe in render so
// we can prerender as much as possible.
//
// For any queries that already exist in the cache, we want to hold back on
// hydrating until _after_ the render phase. The reason for this is that during
// transitions, we don't want the existing queries and observers to update to
// the new data on the current page, only _after_ the transition is committed.
// If the transition is aborted, we will have hydrated any _new_ queries, but
// we throw away the fresh data for any existing ones to avoid unexpectedly
// updating the UI.
const hydrationQueue: DehydratedState['queries'] | undefined =
React.useMemo(() => {
if (state) {
if (typeof state !== 'object') {
return
}
const queryCache = client.getQueryCache()
// State is supplied from the outside and we might as well fail
// gracefully if it has the wrong shape, so while we type `queries`
// as required, we still provide a fallback.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const queries = state.queries || []
const newQueries: DehydratedState['queries'] = []
const existingQueries: DehydratedState['queries'] = []
for (const dehydratedQuery of queries) {
const existingQuery = queryCache.get(dehydratedQuery.queryHash)
if (!existingQuery) {
newQueries.push(dehydratedQuery)
} else {
const hydrationIsNewer =
dehydratedQuery.state.dataUpdatedAt >
existingQuery.state.dataUpdatedAt ||
(dehydratedQuery.promise &&
existingQuery.state.status !== 'pending' &&
existingQuery.state.fetchStatus !== 'fetching' &&
dehydratedQuery.dehydratedAt >
existingQuery.state.dataUpdatedAt)
if (hydrationIsNewer) {
existingQueries.push(dehydratedQuery)
}
}
}
if (newQueries.length > 0) {
// It's actually fine to call this with queries/state that already exists
// in the cache, or is older. hydrate() is idempotent for queries.
// eslint-disable-next-line react-hooks/refs
hydrate(client, { queries: newQueries }, optionsRef.current)
}
if (existingQueries.length > 0) {
return existingQueries
}
}
return undefined
}, [client, state])
React.useEffect(() => {
if (hydrationQueue) {
hydrate(client, { queries: hydrationQueue }, optionsRef.current)
}
}, [client, hydrationQueue])
return children as React.ReactElement
}
+19
View File
@@ -0,0 +1,19 @@
'use client'
import * as React from 'react'
const IsRestoringContext = React.createContext(false)
/**
* If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to
* check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid
* race conditions between the restore and mounting queries.
*
* @returns `true` while a persisted client is being restored, `false` otherwise.
*/
export const useIsRestoring = () => React.useContext(IsRestoringContext)
/**
* The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently
* being restored, read by `useIsRestoring`.
*/
export const IsRestoringProvider = IsRestoringContext.Provider
+86
View File
@@ -0,0 +1,86 @@
'use client'
import * as React from 'react'
import type { QueryClient } from '@tanstack/query-core'
/**
* The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it.
*/
export const QueryClientContext = React.createContext<QueryClient | undefined>(
undefined,
)
/**
* The `useQueryClient` hook returns the current `QueryClient` instance.
*
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current `QueryClient` instance.
* @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the component tree.
*/
export const useQueryClient = (queryClient?: QueryClient) => {
const client = React.useContext(QueryClientContext)
if (queryClient) {
return queryClient
}
if (!client) {
throw new Error('No QueryClient set, use QueryClientProvider to set one')
}
return client
}
/**
* The props accepted by `QueryClientProvider`.
*/
export type QueryClientProviderProps = {
/**
* **Required**
*
* The `QueryClient` instance to provide.
*/
client: QueryClient
/**
* The components that get access to the provided `QueryClient`.
*/
children?: React.ReactNode
}
/**
* Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also
* calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to
* focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or
* comes back online).
*
* @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
*
* @example
* ```tsx
* import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
*
* const queryClient = new QueryClient()
*
* function App() {
* return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
* }
* ```
*/
export const QueryClientProvider = ({
client,
children,
}: QueryClientProviderProps): React.JSX.Element => {
React.useEffect(() => {
client.mount()
return () => {
client.unmount()
}
}, [client])
return (
<QueryClientContext.Provider value={client}>
{children}
</QueryClientContext.Provider>
)
}
+145
View File
@@ -0,0 +1,145 @@
'use client'
import * as React from 'react'
// CONTEXT
export type QueryErrorResetFunction = () => void
export type QueryErrorIsResetFunction = () => boolean
export type QueryErrorClearResetFunction = () => void
export interface QueryErrorResetBoundaryValue {
clearReset: QueryErrorClearResetFunction
isReset: QueryErrorIsResetFunction
reset: QueryErrorResetFunction
}
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
function createValue(): QueryErrorResetBoundaryValue {
let isReset = false
return {
/**
* Clears the reset state, so queries know not to try again until the boundary is reset again.
*/
clearReset: () => {
isReset = false
},
/**
* Resets any query errors within the boundary, so queries know they can try again.
*/
reset: () => {
isReset = true
},
/**
* Returns whether the boundary has been reset and not yet cleared.
*/
isReset: () => {
return isReset
},
}
}
const QueryErrorResetBoundaryContext = React.createContext(createValue())
// HOOK
/**
* This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary
* defined it will reset them globally.
*
* @returns The boundary's {@link QueryErrorResetBoundaryValue}.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { useQueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App({ children }: { children: React.ReactNode }) {
* const { reset } = useQueryErrorResetBoundary()
*
* return (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* {children}
* </ErrorBoundary>
* )
* }
* ```
*/
export const useQueryErrorResetBoundary = () =>
React.useContext(QueryErrorResetBoundaryContext)
// COMPONENT
/**
* A render-prop function usable as `children` on `QueryErrorResetBoundary`.
*
* @param value - The boundary's {@link QueryErrorResetBoundaryValue}.
* @returns The children to render.
*/
export type QueryErrorResetBoundaryFunction = (
value: QueryErrorResetBoundaryValue,
) => React.ReactNode
/**
* The props accepted by `QueryErrorResetBoundary`.
*/
export interface QueryErrorResetBoundaryProps {
/**
* Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and
* returns a node.
*/
children: QueryErrorResetBoundaryFunction | React.ReactNode
}
/**
* When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to
* try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can
* reset any query errors within the boundaries of the component.
*
* @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue}
* if `children` is a function.
*
* @example
* ```tsx
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary } from '@tanstack/react-query'
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Page />
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
export const QueryErrorResetBoundary = ({
children,
}: QueryErrorResetBoundaryProps) => {
const [value] = React.useState(() => createValue())
return (
<QueryErrorResetBoundaryContext.Provider value={value}>
{typeof children === 'function' ? children(value) : children}
</QueryErrorResetBoundaryContext.Provider>
)
}
+78
View File
@@ -0,0 +1,78 @@
'use client'
import * as React from 'react'
import { shouldThrowError } from '@tanstack/query-core'
import type {
DefaultedQueryObserverOptions,
Query,
QueryKey,
QueryObserverResult,
ThrowOnError,
} from '@tanstack/query-core'
import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'
export const ensurePreventErrorBoundaryRetry = <
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: DefaultedQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
errorResetBoundary: QueryErrorResetBoundaryValue,
query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,
) => {
const throwOnError =
query?.state.error && typeof options.throwOnError === 'function'
? shouldThrowError(options.throwOnError, [query.state.error, query])
: options.throwOnError
if (options.suspense || throwOnError) {
// Prevent retrying failed query if the error boundary has not been reset yet
if (!errorResetBoundary.isReset()) {
options.retryOnMount = false
}
}
}
export const useClearResetErrorBoundary = (
errorResetBoundary: QueryErrorResetBoundaryValue,
) => {
React.useEffect(() => {
errorResetBoundary.clearReset()
}, [errorResetBoundary])
}
export const getHasError = <
TData,
TError,
TQueryFnData,
TQueryData,
TQueryKey extends QueryKey,
>({
result,
errorResetBoundary,
throwOnError,
query,
suspense,
}: {
result: QueryObserverResult<TData, TError>
errorResetBoundary: QueryErrorResetBoundaryValue
throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>
query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined
suspense: boolean | undefined
}) => {
return (
result.isError &&
!errorResetBoundary.isReset() &&
!result.isFetching &&
query &&
((suspense && result.data === undefined) ||
shouldThrowError(throwOnError, [result.error, query]))
)
}
+56
View File
@@ -0,0 +1,56 @@
/* istanbul ignore file */
// Re-export core
export * from '@tanstack/query-core'
// React Query
export type * from './types'
export { useQueries } from './useQueries'
export type { QueriesResults, QueriesOptions } from './useQueries'
export { useQuery } from './useQuery'
export { useSuspenseQuery } from './useSuspenseQuery'
export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery'
export { useSuspenseQueries } from './useSuspenseQueries'
export type {
SuspenseQueriesResults,
SuspenseQueriesOptions,
} from './useSuspenseQueries'
export { usePrefetchQuery } from './usePrefetchQuery'
export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery'
export { queryOptions } from './queryOptions'
export type {
DefinedInitialDataOptions,
UndefinedInitialDataOptions,
UnusedSkipTokenOptions,
} from './queryOptions'
export { infiniteQueryOptions } from './infiniteQueryOptions'
export type {
DefinedInitialDataInfiniteOptions,
UndefinedInitialDataInfiniteOptions,
UnusedSkipTokenInfiniteOptions,
} from './infiniteQueryOptions'
export {
QueryClientContext,
QueryClientProvider,
useQueryClient,
} from './QueryClientProvider'
export type { QueryClientProviderProps } from './QueryClientProvider'
export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary'
export { HydrationBoundary } from './HydrationBoundary'
export type { HydrationBoundaryProps } from './HydrationBoundary'
export type {
QueryErrorClearResetFunction,
QueryErrorIsResetFunction,
QueryErrorResetBoundaryFunction,
QueryErrorResetFunction,
} from './QueryErrorResetBoundary'
export {
QueryErrorResetBoundary,
useQueryErrorResetBoundary,
} from './QueryErrorResetBoundary'
export { useIsFetching } from './useIsFetching'
export { useIsMutating, useMutationState } from './useMutationState'
export { useMutation } from './useMutation'
export { mutationOptions } from './mutationOptions'
export { useInfiniteQuery } from './useInfiniteQuery'
export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider'
+319
View File
@@ -0,0 +1,319 @@
import type {
DefaultError,
InfiniteData,
InitialDataFunction,
NonUndefinedGuard,
OmitKeyof,
QueryKey,
QueryKeyWithDataTag,
SkipToken,
} from '@tanstack/query-core'
import type { UseInfiniteQueryOptions } from './types'
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`
* may be `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = UseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?:
| undefined
| NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
| InitialDataFunction<
NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
>
}
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and
* `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be
* `skipToken`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = OmitKeyof<
UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<
UseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>['queryFn'],
SkipToken | undefined
>
}
/**
* The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is
* never `undefined`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = UseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData:
| NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
| (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>)
| undefined
}
/**
* 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`.
* `options.queryKey` is required and is the query key to generate options for.
*
* This overload is selected when `initialData` is set.
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const projectsOptions = infiniteQueryOptions({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* })
*
* function Projects() {
* // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
* // list stays visible alongside the error.
* const { data, isError, error } = useInfiniteQuery(projectsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
* </ul>
* </div>
* )
* }
* ```
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
/**
* 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`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
/**
* 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`.
* `options.queryKey` is required and is the query key to generate options for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or
* automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```tsx
* import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function Comments({ postId }: { postId: string }) {
* const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*
* @see {@link useInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
export function infiniteQueryOptions(options: unknown) {
return options
}
+96
View File
@@ -0,0 +1,96 @@
import type { DefaultError, WithRequired } from '@tanstack/query-core'
import type { UseMutationOptions } from './types'
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
* `useMutationState`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a
* required `mutationKey`.
* @returns The same options object, unchanged.
*
* @example
* Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
* ```tsx
* import { mutationOptions, useMutationState } from '@tanstack/react-query'
*
* const createPostOptions = mutationOptions({
* mutationKey: ['posts', 'create'],
* mutationFn: createPost,
* })
*
* function SavingIndicator() {
* const isCreatingPost = useMutationState({
* filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
* }).length > 0
*
* return isCreatingPost ? <span>Saving…</span> : null
* }
* ```
*/
export function mutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
options: WithRequired<
UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
'mutationKey'
>,
): WithRequired<
UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
'mutationKey'
>
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
* `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters,
* such as `status`.
*
* @see {@link useMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a
* `mutationKey`.
* @returns The same options object, unchanged.
* @remarks See the other overload's example for looking a mutation up via `useMutationState`.
*
* @example
* ```tsx
* import { mutationOptions, useMutation } from '@tanstack/react-query'
*
* export const createPostOptions = mutationOptions({
* mutationFn: createPost,
* })
*
* function CreatePost() {
* const mutation = useMutation(createPostOptions)
* return <button onClick={() => mutation.mutate({ title: 'Hello' })}>Create</button>
* }
* ```
*/
export function mutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
options: Omit<
UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
'mutationKey'
>,
): Omit<
UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
'mutationKey'
>
export function mutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
): UseMutationOptions<TData, TError, TVariables, TOnMutateResult> {
return options
}
+259
View File
@@ -0,0 +1,259 @@
import type {
DefaultError,
InitialDataFunction,
NonUndefinedGuard,
OmitKeyof,
QueryFunction,
QueryKey,
QueryKeyWithDataTag,
SkipToken,
} from '@tanstack/query-core'
import type { UseQueryOptions } from './types'
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be
* `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type UndefinedInitialDataOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?:
| undefined
| InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
| NonUndefinedGuard<TQueryFnData>
}
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
* not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type UnusedSkipTokenOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitKeyof<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
SkipToken | undefined
>
}
/**
* The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never
* `undefined`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type DefinedInitialDataOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData:
| NonUndefinedGuard<TQueryFnData>
| (() => NonUndefinedGuard<TQueryFnData>)
/**
* Optional here, but omitting it is only safe when no fetch will be attempted — for example with
* `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no
* `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this.
*/
queryFn?: QueryFunction<TQueryFnData, TQueryKey>
}
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postsOptions = queryOptions({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* })
*
* function Posts() {
* // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
* // so the list stays visible alongside the error.
* const { data, isError, error } = useQuery(postsOptions)
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* </div>
* )
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
/**
* You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can
* be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and
* is the query key to generate options for.
*
* @see {@link useQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```tsx
* import { queryOptions, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function Post({ id }: { id: string }) {
* const { data, isPending, isError, error } = useQuery(postOptions(id))
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data.title}</h1>
* }
* ```
*
* @example
* A factory that disables the query, type safe, until `postId` is set:
* ```tsx
* import { queryOptions, skipToken, useQuery } from '@tanstack/react-query'
*
* export const postOptions = (postId: number | undefined) =>
* queryOptions({
* queryKey: ['post', postId],
* queryFn: postId != null ? () => fetchPost(postId) : skipToken,
* })
*
* function Post({ postId }: { postId: number | undefined }) {
* const { data, isLoading, isError, error } = useQuery(postOptions(postId))
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
export function queryOptions(options: unknown) {
return options
}
+75
View File
@@ -0,0 +1,75 @@
import type {
DefaultError,
DefaultedQueryObserverOptions,
Query,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'
export const defaultThrowOnError = <
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
_error: TError,
query: Query<TQueryFnData, TError, TData, TQueryKey>,
) => query.state.data === undefined
export const ensureSuspenseTimers = (
defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>,
) => {
if (defaultedOptions.suspense) {
// Handle staleTime to ensure minimum 1000ms in Suspense mode
// This prevents unnecessary refetching when components remount after suspending
const MIN_SUSPENSE_TIME_MS = 1000
const clamp = (value: number | 'static' | undefined) =>
value === 'static'
? value
: Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS)
const originalStaleTime = defaultedOptions.staleTime
defaultedOptions.staleTime =
typeof originalStaleTime === 'function'
? (...args) => clamp(originalStaleTime(...args))
: clamp(originalStaleTime)
if (typeof defaultedOptions.gcTime === 'number') {
defaultedOptions.gcTime = Math.max(
defaultedOptions.gcTime,
MIN_SUSPENSE_TIME_MS,
)
}
}
}
export const shouldSuspend = (
defaultedOptions:
| DefaultedQueryObserverOptions<any, any, any, any, any>
| undefined,
result: QueryObserverResult<any, any>,
) => defaultedOptions?.suspense && result.isPending
export const fetchOptimistic = <
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
defaultedOptions: DefaultedQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
errorResetBoundary: QueryErrorResetBoundaryValue,
) =>
observer.fetchOptimistic(defaultedOptions).catch(() => {
errorResetBoundary.clearReset()
})
+505
View File
@@ -0,0 +1,505 @@
/* istanbul ignore file */
import type {
DefaultError,
DefinedInfiniteQueryObserverResult,
DefinedQueryObserverResult,
DistributiveOmit,
InfiniteData,
InfiniteQueryExecuteOptions,
InfiniteQueryObserverOptions,
InfiniteQueryObserverResult,
MutateFunction,
MutationObserverOptions,
MutationObserverResult,
OmitKeyof,
Override,
QueryExecuteOptions,
QueryKey,
QueryObserverOptions,
QueryObserverResult,
SkipToken,
} from '@tanstack/query-core'
/**
* {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
export type AnyUseBaseQueryOptions = UseBaseQueryOptions<
any,
any,
any,
any,
any
>
/**
* The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} from
* `@tanstack/query-core` with the `react-query`-specific `subscribed` option.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryData - The type of the data actually held in the query cache — the input to `select` and
* `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.
* @template TQueryKey - The type of your `queryKey`.
*/
export interface UseBaseQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> extends QueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
> {
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
*
* @defaultValue true
*/
subscribed?: boolean
}
/**
* The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, except `queryFn`
* is required unless a default query function has been defined.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryData - The type of the data actually held in the query cache — the input to `select` and
* `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.
* @template TQueryKey - The type of your `queryKey`.
*/
export type UsePrefetchQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = DistributiveOmit<
QueryExecuteOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,
* unless a default query function has been defined.
*/
queryFn?: Exclude<
QueryExecuteOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>['queryFn'],
SkipToken
>
}
/**
* The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`,
* 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.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this
* parameter only matters if you reuse these options elsewhere with `select` applied.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type UsePrefetchInfiniteQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = DistributiveOmit<
InfiniteQueryExecuteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — a prefetch always needs a query function to actually run,
* unless a default query function has been defined.
*/
queryFn?: Exclude<
InfiniteQueryExecuteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>['queryFn'],
SkipToken
>
}
/**
* {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
export type AnyUseQueryOptions = UseQueryOptions<any, any, any, any>
/**
* The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which
* `react-query` derives from which hook you call rather than exposing as an option).
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryKey - The type of your `queryKey`.
*/
export interface UseQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> extends OmitKeyof<
UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>,
'suspense'
> {}
/**
* {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions<
any,
any,
any,
any
>
/**
* The options accepted by `useSuspenseQuery`. Same as {@link UseQueryOptions}, minus `enabled`, `throwOnError`,
* and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so those options
* don't apply.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryKey - The type of your `queryKey`.
*/
export interface UseSuspenseQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> extends OmitKeyof<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData'
> {
/**
* `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function
* must always be provided, unless a default query function has been defined.
*/
queryFn?: Exclude<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
SkipToken
>
}
/**
* {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any query in a helper function.
*/
export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions<
any,
any,
any,
any,
any
>
/**
* The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from
* `@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which
* `react-query` derives from which hook you call rather than exposing as an option).
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export interface UseInfiniteQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> extends OmitKeyof<
InfiniteQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
'suspense'
> {
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
*
* @defaultValue true
*/
subscribed?: boolean
}
/**
* {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types
* aren't relevant, e.g. when accepting options for any query in a helper function.
*/
export type AnyUseSuspenseInfiniteQueryOptions =
UseSuspenseInfiniteQueryOptions<any, any, any, any, any>
/**
* The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, minus `enabled`,
* `throwOnError`, and `placeholderData` — Suspense hooks cannot render a "disabled" or "placeholder" state, so
* those options don't apply.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export interface UseSuspenseInfiniteQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> extends OmitKeyof<
UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>,
'queryFn' | 'enabled' | 'throwOnError' | 'placeholderData'
> {
/**
* `skipToken` is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function
* must always be provided, unless a default query function has been defined.
*/
queryFn?: Exclude<
UseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>['queryFn'],
SkipToken
>
}
/**
* The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is
* `pending`. Re-exports {@link QueryObserverResult} from `@tanstack/query-core`. `useInfiniteQuery` returns
* {@link UseInfiniteQueryResult} instead.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type UseBaseQueryResult<
TData = unknown,
TError = DefaultError,
> = QueryObserverResult<TData, TError>
/**
* The result of `useQuery`. Same as {@link UseBaseQueryResult}.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type UseQueryResult<
TData = unknown,
TError = DefaultError,
> = UseBaseQueryResult<TData, TError>
/**
* The result of `useSuspenseQuery`. Same as {@link DefinedUseQueryResult}, minus `isPlaceholderData` — always
* `false` on that type, so this drops the dead field rather than an active state.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type UseSuspenseQueryResult<
TData = unknown,
TError = DefaultError,
> = DistributiveOmit<
DefinedQueryObserverResult<TData, TError>,
'isPlaceholderData'
>
/**
* The result of `useQuery` when `initialData` is set, or of `useSuspenseQuery` before the `isPlaceholderData`
* omission — `data` is never `undefined`. Re-exports {@link DefinedQueryObserverResult} from
* `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type DefinedUseQueryResult<
TData = unknown,
TError = DefaultError,
> = DefinedQueryObserverResult<TData, TError>
/**
* The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is
* `pending`. Re-exports {@link InfiniteQueryObserverResult} from `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type UseInfiniteQueryResult<
TData = unknown,
TError = DefaultError,
> = InfiniteQueryObserverResult<TData, TError>
/**
* The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined`. Re-exports
* {@link DefinedInfiniteQueryObserverResult} from `@tanstack/query-core`.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type DefinedUseInfiniteQueryResult<
TData = unknown,
TError = DefaultError,
> = DefinedInfiniteQueryObserverResult<TData, TError>
/**
* The result of `useSuspenseInfiniteQuery`. Same as {@link DefinedUseInfiniteQueryResult}, minus
* `isPlaceholderData` — Suspense hooks never render placeholder data.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type UseSuspenseInfiniteQueryResult<
TData = unknown,
TError = DefaultError,
> = OmitKeyof<
DefinedInfiniteQueryObserverResult<TData, TError>,
'isPlaceholderData'
>
/**
* {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't
* relevant, e.g. when accepting options for any mutation in a helper function.
*/
export type AnyUseMutationOptions = UseMutationOptions<any, any, any, any>
/**
* The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`,
* minus the internal `_defaulted` flag.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export interface UseMutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> extends OmitKeyof<
MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>,
'_defaulted'
> {}
/**
* The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call
* `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced
* through the mutation result, not thrown.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type UseMutateFunction<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> = (
...args: Parameters<
MutateFunction<TData, TError, TVariables, TOnMutateResult>
>
) => void
/**
* The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a
* promise which can be awaited.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type UseMutateAsyncFunction<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> = MutateFunction<TData, TError, TVariables, TOnMutateResult>
/**
* The result of `useMutation`. Same as {@link MutationObserverResult} from `@tanstack/query-core`, with
* `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type UseBaseMutationResult<
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
> = Override<
MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,
{ mutate: UseMutateFunction<TData, TError, TVariables, TOnMutateResult> }
> & {
/**
* Similar to `mutate`, but returns a promise which can be awaited.
*/
mutateAsync: UseMutateAsyncFunction<
TData,
TError,
TVariables,
TOnMutateResult
>
}
/**
* The result of `useMutation`. Same as {@link UseBaseMutationResult}.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type UseMutationResult<
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
> = UseBaseMutationResult<TData, TError, TVariables, TOnMutateResult>
+143
View File
@@ -0,0 +1,143 @@
'use client'
import * as React from 'react'
import { noop, notifyManager } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
import {
ensurePreventErrorBoundaryRetry,
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'
import { useIsRestoring } from './IsRestoringProvider'
import {
ensureSuspenseTimers,
fetchOptimistic,
shouldSuspend,
} from './suspense'
import type {
QueryClient,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { UseBaseQueryOptions } from './types'
export function useBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: UseBaseQueryOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
Observer: typeof QueryObserver,
queryClient?: QueryClient,
): QueryObserverResult<TData, TError> {
if (process.env.NODE_ENV !== 'production') {
if (typeof options !== 'object' || Array.isArray(options)) {
throw new Error(
'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object',
)
}
}
const isRestoring = useIsRestoring()
const errorResetBoundary = useQueryErrorResetBoundary()
const client = useQueryClient(queryClient)
const defaultedOptions = client.defaultQueryOptions(options)
const query = client
.getQueryCache()
.get<
TQueryFnData,
TError,
TQueryData,
TQueryKey
>(defaultedOptions.queryHash)
if (process.env.NODE_ENV !== 'production') {
if (!defaultedOptions.queryFn) {
console.error(
`[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`,
)
}
}
const subscribed = options.subscribed !== false
// Make sure results are optimistically set in fetching state before subscribing or updating options
defaultedOptions._optimisticResults = isRestoring
? 'isRestoring'
: subscribed
? 'optimistic'
: undefined
ensureSuspenseTimers(defaultedOptions)
ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
useClearResetErrorBoundary(errorResetBoundary)
const [observer] = React.useState(
() =>
new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
client,
defaultedOptions,
),
)
// note: this must be called before useSyncExternalStore
const result = observer.getOptimisticResult(defaultedOptions)
const shouldSubscribe = !isRestoring && subscribed
React.useSyncExternalStore(
React.useCallback(
(onStoreChange) => {
const unsubscribe = shouldSubscribe
? observer.subscribe(notifyManager.batchCalls(onStoreChange))
: noop
// Update result to make sure we did not miss any query updates
// between creating the observer and subscribing to it.
observer.updateResult()
return unsubscribe
},
[observer, shouldSubscribe],
),
() => observer.getCurrentResult(),
() => observer.getCurrentResult(),
)
React.useEffect(() => {
observer.setOptions(defaultedOptions)
}, [defaultedOptions, observer])
// Handle suspense
if (shouldSuspend(defaultedOptions, result)) {
throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
}
// Handle error boundary
if (
getHasError({
result,
errorResetBoundary,
throwOnError: defaultedOptions.throwOnError,
query,
suspense: defaultedOptions.suspense,
})
) {
throw result.error
}
// Handle result property usage tracking
return !defaultedOptions.notifyOnChangeProps
? observer.trackResult(result)
: result
}
+373
View File
@@ -0,0 +1,373 @@
'use client'
import { InfiniteQueryObserver } from '@tanstack/query-core'
import { useBaseQuery } from './useBaseQuery'
import type {
DefaultError,
InfiniteData,
QueryClient,
QueryKey,
QueryObserver,
} from '@tanstack/query-core'
import type {
DefinedUseInfiniteQueryResult,
UseInfiniteQueryOptions,
UseInfiniteQueryResult,
} from './types'
import type {
DefinedInitialDataInfiniteOptions,
UndefinedInitialDataInfiniteOptions,
} from './infiniteQueryOptions'
/**
* The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
*
* This overload is selected when `initialData` is set.
*
* @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`.
* @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` set.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
* `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
* `InfiniteData<TQueryFnData>` shape.
*
* @example
* ```tsx
* import { useInfiniteQuery } from '@tanstack/react-query'
*
* function Projects() {
* // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
* // list stays visible alongside the error.
* const { data, isError, error } = useInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* })
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
* </ul>
* </div>
* )
* }
* ```
*/
export function useInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
queryClient?: QueryClient,
): DefinedUseInfiniteQueryResult<TData, TError>
/**
* The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
*
* @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`.
* @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
* `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
* `InfiniteData<TQueryFnData>` shape.
*
* @example
* Fetching the next page from a "Load More" button click:
* ```tsx
* import { useInfiniteQuery } from '@tanstack/react-query'
*
* function Projects() {
* const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
* useInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <>
* <ul>
* {data.pages.map((page) =>
* page.projects.map((project) => <li key={project.id}>{project.name}</li>),
* )}
* </ul>
* <button
* onClick={() => fetchNextPage()}
* disabled={!hasNextPage || isFetching}
* >
* {isFetchingNextPage
* ? 'Loading more...'
* : hasNextPage
* ? 'Load More'
* : 'Nothing more to load'}
* </button>
* </>
* )
* }
* ```
*
* @example
* Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
* sentinel element after the list:
* ```tsx
* import { useInfiniteQuery } from '@tanstack/react-query'
* import { useEffect, useRef } from 'react'
*
* function Projects() {
* const {
* data,
* isPending,
* isError,
* error,
* fetchNextPage,
* hasNextPage,
* isFetching,
* isFetchingNextPage,
* } = useInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* const sentinelRef = useRef<HTMLDivElement>(null)
*
* useEffect(() => {
* const sentinel = sentinelRef.current
* if (sentinel == null || !hasNextPage || isFetching) return
*
* const observer = new IntersectionObserver(([entry]) => {
* if (entry?.isIntersecting) fetchNextPage()
* })
* observer.observe(sentinel)
*
* return () => observer.disconnect()
* }, [hasNextPage, isFetching, fetchNextPage])
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <>
* <ul>
* {data.pages.map((page) =>
* page.projects.map((project) => <li key={project.id}>{project.name}</li>),
* )}
* </ul>
* <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
* </>
* )
* }
* ```
*/
export function useInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
queryClient?: QueryClient,
): UseInfiniteQueryResult<TData, TError>
/**
* The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
*
* @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`.
* @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
* `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
* `InfiniteData<TQueryFnData>` shape.
*
* @example
* Fetching the next page from a "Load More" button click:
* ```tsx
* import { useInfiniteQuery } from '@tanstack/react-query'
*
* function Projects() {
* const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
* useInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <>
* <ul>
* {data.pages.map((page) =>
* page.projects.map((project) => <li key={project.id}>{project.name}</li>),
* )}
* </ul>
* <button
* onClick={() => fetchNextPage()}
* disabled={!hasNextPage || isFetching}
* >
* {isFetchingNextPage
* ? 'Loading more...'
* : hasNextPage
* ? 'Load More'
* : 'Nothing more to load'}
* </button>
* </>
* )
* }
* ```
*
* @example
* Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
* sentinel element after the list:
* ```tsx
* import { useInfiniteQuery } from '@tanstack/react-query'
* import { useEffect, useRef } from 'react'
*
* function Projects() {
* const {
* data,
* isPending,
* isError,
* error,
* fetchNextPage,
* hasNextPage,
* isFetching,
* isFetchingNextPage,
* } = useInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* const sentinelRef = useRef<HTMLDivElement>(null)
*
* useEffect(() => {
* const sentinel = sentinelRef.current
* if (sentinel == null || !hasNextPage || isFetching) return
*
* const observer = new IntersectionObserver(([entry]) => {
* if (entry?.isIntersecting) fetchNextPage()
* })
* observer.observe(sentinel)
*
* return () => observer.disconnect()
* }, [hasNextPage, isFetching, fetchNextPage])
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <>
* <ul>
* {data.pages.map((page) =>
* page.projects.map((project) => <li key={project.id}>{project.name}</li>),
* )}
* </ul>
* <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
* </>
* )
* }
* ```
*
* @example
* A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn`
* instead of setting `enabled: false`:
* ```tsx
* import { skipToken, useInfiniteQuery } from '@tanstack/react-query'
*
* function Comments({ postId }: { postId: string | undefined }) {
* // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
* const { data, isLoading, isError, error } = useInfiniteQuery({
* queryKey: ['post', postId, 'comments'],
* queryFn:
* postId != null
* ? ({ pageParam }) => fetchComments(postId, pageParam)
* : skipToken,
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
* </ul>
* )
* }
* ```
*/
export function useInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
queryClient?: QueryClient,
): UseInfiniteQueryResult<TData, TError>
export function useInfiniteQuery(
options: UseInfiniteQueryOptions,
queryClient?: QueryClient,
) {
return useBaseQuery(
options,
InfiniteQueryObserver as typeof QueryObserver,
queryClient,
)
}
+60
View File
@@ -0,0 +1,60 @@
'use client'
import * as React from 'react'
import { notifyManager } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type { QueryClient, QueryFilters } from '@tanstack/query-core'
/**
* The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in
* the background (useful for app-wide loading indicators).
*
* @param filters - The {@link QueryFilters} to narrow down the matched queries.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns Will be the `number` of the queries that your application is currently loading or fetching in the
* background.
*
* @example
* ```tsx
* import { useIsFetching } from '@tanstack/react-query'
*
* function PostsFetchingIndicator() {
* // How many queries matching the posts prefix are fetching?
* const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
*
* return isFetchingPosts ? <span>Refreshing posts...</span> : null
* }
* ```
*
* @example
* A global loading indicator for any query fetching in the background, not just the ones on screen:
* ```tsx
* import { useIsFetching } from '@tanstack/react-query'
*
* function GlobalLoadingIndicator() {
* const isFetching = useIsFetching()
*
* return isFetching ? (
* <div>Queries are fetching in the background...</div>
* ) : null
* }
* ```
*/
export function useIsFetching(
filters?: QueryFilters,
queryClient?: QueryClient,
): number {
const client = useQueryClient(queryClient)
const queryCache = client.getQueryCache()
return React.useSyncExternalStore(
React.useCallback(
(onStoreChange) =>
queryCache.subscribe(notifyManager.batchCalls(onStoreChange)),
[queryCache],
),
() => client.isFetching(filters),
() => client.isFetching(filters),
)
}
+245
View File
@@ -0,0 +1,245 @@
'use client'
import * as React from 'react'
import {
MutationObserver,
noop,
notifyManager,
shouldThrowError,
} from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type {
UseMutateFunction,
UseMutationOptions,
UseMutationResult,
} from './types'
import type { DefaultError, QueryClient } from '@tanstack/query-core'
// HOOK
/**
* Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
* `useMutation` is the hook for that.
*
* @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look
* the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
* @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
* argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
* mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
* fire only for the latest call you've made, and only while the component is still mounted — unmounting before
* the mutation settles removes the subscription and prevents them from firing.
*
* @example
* ```tsx
* import { useMutation, useQueryClient } from '@tanstack/react-query'
*
* function AddTodo() {
* const queryClient = useQueryClient()
*
* const addMutation = useMutation({
* mutationFn: addTodo,
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
* })
*
* return (
* <button
* onClick={() =>
* addMutation.mutate('Item', {
* onError: (error) => console.error('Failed to add item:', error),
* })
* }
* >
* Add
* </button>
* )
* }
* ```
*
* @example
* Rendering the mutation's own state, rather than just firing it off:
* ```tsx
* import { useMutation, useQueryClient } from '@tanstack/react-query'
*
* function AddTodo() {
* const queryClient = useQueryClient()
*
* const addMutation = useMutation({
* mutationFn: addTodo,
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
* })
*
* return (
* <div>
* {addMutation.isPending ? (
* 'Adding todo...'
* ) : (
* <>
* {addMutation.isError ? (
* <div>An error occurred: {addMutation.error.message}</div>
* ) : null}
* <button onClick={() => addMutation.mutate('Item')}>Add</button>
* </>
* )}
* </div>
* )
* }
* ```
*
* @example
* Optimistic update via `onMutate`, rolling back on `onError`:
* ```tsx
* import { useMutation, useQueryClient } from '@tanstack/react-query'
*
* function AddTodo() {
* const queryClient = useQueryClient()
*
* const addMutation = useMutation({
* mutationFn: addTodo,
* onMutate: async (newTodo) => {
* await queryClient.cancelQueries({ queryKey: ['todos'] })
* const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
*
* queryClient.setQueryData<Array<string>>(['todos'], (old) => [
* ...(old ?? []),
* newTodo,
* ])
*
* // Passed to `onError` as `onMutateResult` if the mutation fails.
* return { previousTodos }
* },
* onError: (_err, _newTodo, onMutateResult) => {
* queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
* },
* onSettled: () => {
* queryClient.invalidateQueries({ queryKey: ['todos'] })
* },
* })
*
* return (
* <button onClick={() => addMutation.mutate('Item')}>Add</button>
* )
* }
* ```
*
* @example
* Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
* promise per call instead, so you can wait for all of them when they succeed:
* ```tsx
* import { useMutation, useQueryClient } from '@tanstack/react-query'
*
* function AddTodos() {
* const queryClient = useQueryClient()
*
* const addMutation = useMutation({
* mutationFn: addTodo,
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
* })
*
* async function handleAddAll(todos: Array<string>) {
* try {
* await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
* } catch (error) {
* console.error('Failed to add todos:', error)
* }
* }
*
* return (
* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
* Add all
* </button>
* )
* }
* ```
*
* @example
* If some of the mutations above can fail independently of the others, and you want to know which ones
* did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
* `Promise.allSettled`:
* ```tsx
* import { useMutation, useQueryClient } from '@tanstack/react-query'
*
* function AddTodos() {
* const queryClient = useQueryClient()
*
* const addMutation = useMutation({
* mutationFn: addTodo,
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
* })
*
* async function handleAddAll(todos: Array<string>) {
* const addResults = await Promise.allSettled(
* todos.map((todo) => addMutation.mutateAsync(todo)),
* )
*
* addResults.forEach((addResult, index) => {
* if (addResult.status === 'rejected') {
* console.error(`Failed to add "${todos[index]}":`, addResult.reason)
* }
* })
* }
*
* return (
* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
* Add all
* </button>
* )
* }
* ```
*/
export function useMutation<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
queryClient?: QueryClient,
): UseMutationResult<TData, TError, TVariables, TOnMutateResult> {
const client = useQueryClient(queryClient)
const [observer] = React.useState(
() =>
new MutationObserver<TData, TError, TVariables, TOnMutateResult>(
client,
options,
),
)
React.useEffect(() => {
observer.setOptions(options)
}, [observer, options])
const result = React.useSyncExternalStore(
React.useCallback(
(onStoreChange) =>
observer.subscribe(notifyManager.batchCalls(onStoreChange)),
[observer],
),
() => observer.getCurrentResult(),
() => observer.getCurrentResult(),
)
const mutate = React.useCallback<
UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
>(
(
...args: Parameters<
UseMutateFunction<TData, TError, TVariables, TOnMutateResult>
>
) => {
observer.mutate(args[0] as TVariables, args[1]).catch(noop)
},
[observer],
)
if (
result.error &&
shouldThrowError(observer.options.throwOnError, [result.error])
) {
throw result.error
}
return { ...result, mutate, mutateAsync: result.mutate }
}
+194
View File
@@ -0,0 +1,194 @@
'use client'
import * as React from 'react'
import { notifyManager, replaceEqualDeep } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type {
Mutation,
MutationCache,
MutationFilters,
MutationState,
QueryClient,
} from '@tanstack/query-core'
/**
* The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
* (useful for app-wide loading indicators).
*
* @param filters - The {@link MutationFilters} to narrow down the matched mutations.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns Will be the `number` of the mutations that your application currently has `pending`.
*
* @example
* ```tsx
* import { useIsMutating } from '@tanstack/react-query'
*
* function PostsMutatingIndicator() {
* // How many mutations matching the posts prefix are in progress?
* const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
*
* return isMutatingPosts ? <span>Saving posts...</span> : null
* }
* ```
*/
export function useIsMutating(
filters?: MutationFilters,
queryClient?: QueryClient,
): number {
const client = useQueryClient(queryClient)
return useMutationState(
{ filters: { ...filters, status: 'pending' } },
client,
).length
}
type MutationTypeFromResult<TResult> = [TResult] extends [
MutationState<
infer TData,
infer TError,
infer TVariables,
infer TOnMutateResult
>,
]
? Mutation<TData, TError, TVariables, TOnMutateResult>
: Mutation
type MutationStateOptions<
TResult = MutationState,
TMutation extends Mutation<any, any, any, any> =
MutationTypeFromResult<TResult>,
> = {
filters?: MutationFilters
select?: (mutation: TMutation) => TResult
}
function getResult<
TResult = MutationState,
TMutation extends Mutation<any, any, any, any> =
MutationTypeFromResult<TResult>,
>(
mutationCache: MutationCache,
options: MutationStateOptions<TResult, TMutation>,
): Array<TResult> {
return mutationCache
.findAll(options.filters)
.map(
(mutation): TResult =>
(options.select
? options.select(mutation as TMutation)
: mutation.state) as TResult,
)
}
/**
* `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
* `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
* state.
*
* @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
* mutation state.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns Will be an Array of whatever `select` returns for each matching mutation.
*
* @example
* Get all variables of all running mutations:
* ```tsx
* import { useMutationState } from '@tanstack/react-query'
*
* function PendingPosts() {
* const pendingVariables = useMutationState({
* filters: { status: 'pending' },
* select: (mutation) => mutation.state.variables,
* })
*
* return <>{pendingVariables.length} posts saving...</>
* }
* ```
*
* @example
* Get all data for specific mutations via the `mutationKey`:
* ```tsx
* import { useMutation, useMutationState } from '@tanstack/react-query'
*
* const mutationKey = ['posts']
*
* function Posts() {
* // Some mutation that we want to get the state for
* const mutation = useMutation({
* mutationKey,
* mutationFn: createPosts,
* })
*
* const savedPosts = useMutationState({
* // this mutation key needs to match the mutation key of the given mutation (see above)
* filters: { mutationKey, status: 'success' },
* select: (mutation) => mutation.state.data,
* })
*
* return (
* <button onClick={() => mutation.mutate(['New Post'])}>
* Create post ({savedPosts.length} saved so far)
* </button>
* )
* }
* ```
*
* @example
* Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
* entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
* last item that `useMutationState` returns to get the latest successful invocation:
* ```tsx
* import { useMutationState } from '@tanstack/react-query'
*
* function LatestPost() {
* const savedPosts = useMutationState({
* filters: { mutationKey: ['posts'], status: 'success' },
* select: (mutation) => mutation.state.data,
* })
*
* const latestSavedPost = savedPosts[savedPosts.length - 1]
*
* return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>
* }
* ```
*/
export function useMutationState<
TResult = MutationState,
TMutation extends Mutation<any, any, any, any> =
MutationTypeFromResult<TResult>,
>(
options: MutationStateOptions<TResult, TMutation> = {},
queryClient?: QueryClient,
): Array<TResult> {
const mutationCache = useQueryClient(queryClient).getMutationCache()
const optionsRef = React.useRef(options)
const result = React.useRef<Array<TResult>>(null)
if (result.current === null) {
result.current = getResult(mutationCache, options)
}
React.useEffect(() => {
optionsRef.current = options
})
return React.useSyncExternalStore(
React.useCallback(
(onStoreChange) =>
mutationCache.subscribe(() => {
const nextResult = replaceEqualDeep(
result.current,
getResult(mutationCache, optionsRef.current),
)
if (result.current !== nextResult) {
result.current = nextResult
notifyManager.schedule(onStoreChange)
}
}),
[mutationCache],
),
() => result.current,
() => result.current,
)!
}
@@ -0,0 +1,77 @@
import { noop } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type {
DefaultError,
InfiniteData,
QueryClient,
QueryKey,
} from '@tanstack/query-core'
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
* `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless
* a default query function has been defined.
*
* `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
* as well as pageParam information, and should return a single variable that will be passed to your query
* function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
*
* 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 queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns `void` — nothing is returned.
*
* @example
* ```tsx
* import { Suspense } from 'react'
* import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query'
*
* const projectsOptions = infiniteQueryOptions({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* function App() {
* // Fire the prefetch during render, before the suspense boundary below.
* usePrefetchInfiniteQuery(projectsOptions)
*
* return (
* <Suspense fallback={<h1>Loading projects...</h1>}>
* <Projects />
* </Suspense>
* )
* }
* ```
*/
export function usePrefetchInfiniteQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UsePrefetchInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
queryClient?: QueryClient,
): void {
const client = useQueryClient(queryClient)
if (!client.getQueryState(options.queryKey)) {
void client.infiniteQuery(options).catch(noop)
}
}
+63
View File
@@ -0,0 +1,63 @@
import { noop } from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
import type { UsePrefetchQueryOptions } from './types'
/**
* `usePrefetchQuery` 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 `useSuspenseQuery`. You can pass everything to
* `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and
* `queryFn` is required unless a default query function has been defined.
*
* 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 UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns `void` — nothing is returned.
*
* @example
* ```tsx
* import { Suspense } from 'react'
* import { usePrefetchQuery } from '@tanstack/react-query'
*
* function App() {
* // Fire the prefetch during render, before the suspense boundary below.
* usePrefetchQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
*
* return (
* <Suspense fallback={<h1>Loading posts...</h1>}>
* <Posts />
* </Suspense>
* )
* }
* ```
*/
export function usePrefetchQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UsePrefetchQueryOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
queryClient?: QueryClient,
): void {
const client = useQueryClient(queryClient)
if (!client.getQueryState(options.queryKey)) {
void client.query(options).catch(noop)
}
}
+494
View File
@@ -0,0 +1,494 @@
'use client'
import * as React from 'react'
import {
QueriesObserver,
QueryObserver,
noop,
notifyManager,
} from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import { useIsRestoring } from './IsRestoringProvider'
import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
import {
ensurePreventErrorBoundaryRetry,
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'
import {
ensureSuspenseTimers,
fetchOptimistic,
shouldSuspend,
} from './suspense'
import type {
DefinedUseQueryResult,
UseQueryOptions,
UseQueryResult,
} from './types'
import type {
DefaultError,
OmitKeyof,
QueriesObserverOptions,
QueriesPlaceholderDataFunction,
QueryClient,
QueryFunction,
QueryKey,
QueryObserverOptions,
ThrowOnError,
} from '@tanstack/query-core'
// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
// `placeholderData` function always gets undefined passed
type UseQueryOptionsForUseQueries<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitKeyof<
UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'placeholderData' | 'subscribed'
> & {
placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
}
// Avoid TS depth-limit error in case of large array literal
type MAXIMUM_DEPTH = 20
// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
type SkipTokenForUseQueries = symbol
type GetUseQueryOptionsForUseQueries<T> =
// Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
T extends {
queryFnData: infer TQueryFnData
error?: infer TError
data: infer TData
}
? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? UseQueryOptionsForUseQueries<TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? UseQueryOptionsForUseQueries<unknown, TError, TData>
: // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
T extends [infer TQueryFnData, infer TError, infer TData]
? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
: T extends [infer TQueryFnData, infer TError]
? UseQueryOptionsForUseQueries<TQueryFnData, TError>
: T extends [infer TQueryFnData]
? UseQueryOptionsForUseQueries<TQueryFnData>
: // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, infer TQueryKey>
| SkipTokenForUseQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? UseQueryOptionsForUseQueries<
TQueryFnData,
unknown extends TError ? DefaultError : TError,
unknown extends TData ? TQueryFnData : TData,
TQueryKey
>
: // Fallback
UseQueryOptionsForUseQueries
// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult
type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
initialData?: infer TInitialData
}
? unknown extends TInitialData
? UseQueryResult<TData, TError>
: TInitialData extends TData
? DefinedUseQueryResult<TData, TError>
: TInitialData extends () => infer TInitialDataResult
? unknown extends TInitialDataResult
? UseQueryResult<TData, TError>
: TInitialDataResult extends TData
? DefinedUseQueryResult<TData, TError>
: UseQueryResult<TData, TError>
: UseQueryResult<TData, TError>
: UseQueryResult<TData, TError>
type GetUseQueryResult<T> =
// Part 1: responsible for mapping explicit type parameter to function result, if object
T extends { queryFnData: any; error?: infer TError; data: infer TData }
? GetDefinedOrUndefinedQueryResult<T, TData, TError>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? GetDefinedOrUndefinedQueryResult<T, TData, TError>
: // Part 2: responsible for mapping explicit type parameter to function result, if tuple
T extends [any, infer TError, infer TData]
? GetDefinedOrUndefinedQueryResult<T, TData, TError>
: T extends [infer TQueryFnData, infer TError]
? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
: T extends [infer TQueryFnData]
? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>
: // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, any>
| SkipTokenForUseQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? GetDefinedOrUndefinedQueryResult<
T,
unknown extends TData ? TQueryFnData : TData,
unknown extends TError ? DefaultError : TError
>
: // Fallback
UseQueryResult
/**
* The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's
* `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.
* `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls
* back to a single homogeneous options type.
*
* @template T - The type of the `queries` array as written at the call site.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant
* to be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
export type QueriesOptions<
T extends Array<any>,
TResults extends Array<any> = [],
TDepth extends ReadonlyArray<number> = [],
> = TDepth['length'] extends MAXIMUM_DEPTH
? Array<UseQueryOptionsForUseQueries>
: T extends []
? []
: T extends [infer Head]
? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
: T extends [infer Head, ...infer Tails]
? QueriesOptions<
[...Tails],
[...TResults, GetUseQueryOptionsForUseQueries<Head>],
[...TDepth, 1]
>
: ReadonlyArray<unknown> extends T
? T
: // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
// use this to infer the param types in the case of Array.map() argument
T extends Array<
UseQueryOptionsForUseQueries<
infer TQueryFnData,
infer TError,
infer TData,
infer TQueryKey
>
>
? Array<
UseQueryOptionsForUseQueries<
TQueryFnData,
TError,
TData,
TQueryKey
>
>
: // Fallback
Array<UseQueryOptionsForUseQueries>
/**
* The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each
* tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped
* per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a
* single homogeneous {@link UseQueryResult} type.
*
* @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant
* to be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
export type QueriesResults<
T extends Array<any>,
TResults extends Array<any> = [],
TDepth extends ReadonlyArray<number> = [],
> = TDepth['length'] extends MAXIMUM_DEPTH
? Array<UseQueryResult>
: T extends []
? []
: T extends [infer Head]
? [...TResults, GetUseQueryResult<Head>]
: T extends [infer Head, ...infer Tails]
? QueriesResults<
[...Tails],
[...TResults, GetUseQueryResult<Head>],
[...TDepth, 1]
>
: { [K in keyof T]: GetUseQueryResult<T[K]> }
/**
* The `useQueries` hook can be used to fetch a variable number of queries.
*
* The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level
* `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom
* `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query.
*
* Having the same query key more than once in the array of query objects may cause some data to be shared
* between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
* structure.
*
* The `combine` option can be used to combine the results of the queries into a single value. The result will
* be structurally shared to be as referentially stable as possible.
*
* @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results
* changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap
* it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to
* avoid that.
*
* Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling
* `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter
* of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls
* back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate
* the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in
* a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same
* limitation applies to {@link useSuspenseQueries}.
*
* `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
* previously rendered queries, because the number of queries can differ between renders.
* @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
* will be used.
* @returns The combined result. Without `combine`, this is an array with all the query results, in the same
* order as the input. When `combine` is provided, this is the value returned by `combine` instead.
*
* @example
* ```tsx
* import { useQueries } from '@tanstack/react-query'
*
* function Posts({ ids }: { ids: Array<number> }) {
* const postQueries = useQueries({
* queries: ids.map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* staleTime: Infinity,
* })),
* })
*
* return (
* <ul>
* {postQueries.map((query, index) => {
* if (query.isPending) return <li key={ids[index]}>Loading...</li>
* if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
* return <li key={ids[index]}>{query.data.title}</li>
* })}
* </ul>
* )
* }
* ```
*
* @example
* Combining results into a single value:
* ```tsx
* import { useQueries } from '@tanstack/react-query'
*
* function Posts({ ids }: { ids: Array<number> }) {
* const { data, isPending, isError } = useQueries({
* queries: ids.map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })),
* combine: (postQueries) => {
* return {
* data: postQueries.map((query) => query.data),
* isPending: postQueries.some((query) => query.isPending),
* isError: postQueries.some((query) => query.isError),
* }
* },
* })
*
* if (isPending) return 'Loading...'
* if (isError) return 'Error loading posts'
*
* return (
* <ul>
* {data.map((post) => (
* <li key={post?.id}>{post?.title}</li>
* ))}
* </ul>
* )
* }
* ```
*
* @example
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
* resolved before it reaches `useQueries`:
* ```tsx
* import { queryOptions, useQueries } from '@tanstack/react-query'
*
* const postOptions = (id: number) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* function PostTitle({ id }: { id: number }) {
* const [{ data: broken }] = useQueries({
* queries: [
* {
* ...postOptions(id),
* // ❌ `data` is `unknown` here
* select: (data) => data.title,
* },
* ],
* })
*
* const [{ data: fixed }] = useQueries({
* queries: [
* queryOptions({
* ...postOptions(id),
* // ✅ `data` is `Post`
* select: (data) => data.title,
* }),
* ],
* })
*
* return <h1>{fixed}</h1>
* }
* ```
*/
export function useQueries<
T extends Array<any>,
TCombinedResult = QueriesResults<T>,
>(
{
queries,
...options
}: {
/**
* An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and
* `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
* `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
* and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
*/
queries:
| readonly [...QueriesOptions<T>]
| readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
/**
* Use this to combine the results of the queries into a single value. The result will be structurally
* shared to be as referentially stable as possible.
*/
combine?: (result: QueriesResults<T>) => TCombinedResult
/**
* Set this to `false` to unsubscribe this observer from updates to the query cache.
*
* @defaultValue true
*/
subscribed?: boolean
},
queryClient?: QueryClient,
): TCombinedResult {
const client = useQueryClient(queryClient)
const isRestoring = useIsRestoring()
const errorResetBoundary = useQueryErrorResetBoundary()
const subscribed = options.subscribed !== false
const defaultedQueries = React.useMemo(
() =>
queries.map((opts) => {
const defaultedOptions = client.defaultQueryOptions(
opts as QueryObserverOptions,
)
// Make sure the results are already in fetching state before subscribing or updating options
defaultedOptions._optimisticResults = isRestoring
? 'isRestoring'
: subscribed
? 'optimistic'
: undefined
return defaultedOptions
}),
[queries, client, isRestoring, subscribed],
)
defaultedQueries.forEach((queryOptions) => {
ensureSuspenseTimers(queryOptions)
const query = client.getQueryCache().get(queryOptions.queryHash)
ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
})
useClearResetErrorBoundary(errorResetBoundary)
const [observer] = React.useState(
() =>
new QueriesObserver<TCombinedResult>(
client,
defaultedQueries,
options as QueriesObserverOptions<TCombinedResult>,
),
)
// note: this must be called before useSyncExternalStore
const [optimisticResult, getCombinedResult, trackResult] =
observer.getOptimisticResult(
defaultedQueries,
(options as QueriesObserverOptions<TCombinedResult>).combine,
)
const shouldSubscribe = !isRestoring && subscribed
React.useSyncExternalStore(
React.useCallback(
(onStoreChange) =>
shouldSubscribe
? observer.subscribe(notifyManager.batchCalls(onStoreChange))
: noop,
[observer, shouldSubscribe],
),
() => observer.getCurrentResult(),
() => observer.getCurrentResult(),
)
React.useEffect(() => {
observer.setQueries(
defaultedQueries,
options as QueriesObserverOptions<TCombinedResult>,
)
}, [defaultedQueries, options, observer])
const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>
shouldSuspend(defaultedQueries[index], result),
)
const suspensePromises = shouldAtLeastOneSuspend
? optimisticResult.flatMap((result, index) => {
const opts = defaultedQueries[index]
if (opts && shouldSuspend(opts, result)) {
const queryObserver = new QueryObserver(client, opts)
return fetchOptimistic(opts, queryObserver, errorResetBoundary)
}
return []
})
: []
if (suspensePromises.length > 0) {
throw Promise.all(suspensePromises)
}
const firstSingleResultWhichShouldThrow = optimisticResult.find(
(result, index) => {
const query = defaultedQueries[index]
return (
query &&
getHasError({
result,
errorResetBoundary,
throwOnError: query.throwOnError,
query: client.getQueryCache().get(query.queryHash),
suspense: query.suspense,
})
)
},
)
if (firstSingleResultWhichShouldThrow) {
throw firstSingleResultWhichShouldThrow.error
}
return getCombinedResult(trackResult())
}
+293
View File
@@ -0,0 +1,293 @@
'use client'
import { QueryObserver } from '@tanstack/query-core'
import { useBaseQuery } from './useBaseQuery'
import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
import type {
DefinedUseQueryResult,
UseQueryOptions,
UseQueryResult,
} from './types'
import type {
DefinedInitialDataOptions,
UndefinedInitialDataOptions,
} from './queryOptions'
/**
* This overload is selected when `initialData` is set, so the resulting `data` is never `undefined`.
*
* @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
* @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` set.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current query result, typed so that `status` is `success` — or `error` if a fetch attempt
* fails while keeping the existing data (`status` never resolves to `pending` in this overload's type,
* since `initialData` guarantees data upfront). `isSuccess`/`isError` are derived booleans for convenience.
*
* @example
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function Posts() {
* // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails,
* // so the list stays visible alongside the error.
* const { data, isError, error } = useQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* })
*
* return (
* <div>
* {isError ? <span>Error: {error.message}</span> : null}
* <ul>
* {data.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* </div>
* )
* }
* ```
*/
export function useQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): DefinedUseQueryResult<TData, TError>
/**
* @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
* @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
* the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
* are derived booleans for convenience.
*
* @example
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function Posts() {
* const { status, data, error, isFetching } = useQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
*
* if (status === 'pending') return 'Loading...'
* if (status === 'error') return <span>Error: {error.message}</span>
*
* return (
* <div>
* <ul>
* {data.map((post) => (
* <li key={post.id}>{post.title}</li>
* ))}
* </ul>
* <div>{isFetching ? 'Background Updating...' : ' '}</div>
* </div>
* )
* }
* ```
*
* @example
* The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you:
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function Posts() {
* const { isPending, isError, data, error } = useQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <ul>
* {data.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* )
* }
* ```
*/
export function useQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): UseQueryResult<TData, TError>
/**
* @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
* @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The current query result. `status` is `pending` if there is no cached data to display, `error` if
* the last fetch attempt failed, or `success` if the query has data to display. `isPending`/`isSuccess`/`isError`
* are derived booleans for convenience.
*
* @example
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function Posts() {
* const { status, data, error, isFetching } = useQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
*
* if (status === 'pending') return 'Loading...'
* if (status === 'error') return <span>Error: {error.message}</span>
*
* return (
* <div>
* <ul>
* {data.map((post) => (
* <li key={post.id}>{post.title}</li>
* ))}
* </ul>
* <div>{isFetching ? 'Background Updating...' : ' '}</div>
* </div>
* )
* }
* ```
*
* @example
* `select` derives whatever `data` a component needs from the cached value, without changing what's
* actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function PostCount() {
* const { data, isPending, isError, error } = useQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* select: (posts) => posts.length,
* })
*
* if (isPending) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <span>{data} posts</span>
* }
* ```
*
* @example
* A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the
* loading state doesn't show while the query is disabled:
* ```tsx
* import { useQuery } from '@tanstack/react-query'
*
* function Post({ postId }: { postId: number | undefined }) {
* const { data, isLoading, isError, error } = useQuery({
* queryKey: ['post', postId],
* queryFn: () => fetchPost(postId!),
* enabled: postId != null,
* })
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*
* @example
* The same dependent query, type safe: `skipToken` disables the query without needing the
* non-null assertion above, since `queryFn` is only ever called when `postId` is defined.
* `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you
* need to trigger the query manually:
* ```tsx
* import { skipToken, useQuery } from '@tanstack/react-query'
*
* function Post({ postId }: { postId: number | undefined }) {
* const { data, isLoading, isError, error } = useQuery({
* queryKey: ['post', postId],
* queryFn: postId != null ? () => fetchPost(postId) : skipToken,
* })
*
* if (postId == null) return 'Select a post'
* if (isLoading) return 'Loading...'
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*
* @example
* Seeding a detail query from an already-cached list, to skip the loading state:
* ```tsx
* import { useQuery, useQueryClient } from '@tanstack/react-query'
*
* function Post({ postId }: { postId: number }) {
* const queryClient = useQueryClient()
*
* const { data, isError, error } = useQuery({
* queryKey: ['post', postId],
* queryFn: () => fetchPost(postId),
* initialData: () =>
* queryClient
* .getQueryData<Array<Post>>(['posts'])
* ?.find((post) => post.id === postId),
* })
*
* if (isError) return <span>Error: {error.message}</span>
*
* return <h1>{data?.title}</h1>
* }
* ```
*
* @example
* Paginated data, keeping the previous page's data visible while the next page loads:
* ```tsx
* import { keepPreviousData, useQuery } from '@tanstack/react-query'
* import { useState } from 'react'
*
* function Posts() {
* const [page, setPage] = useState(0)
*
* const { data, isPlaceholderData, isError, error } = useQuery({
* queryKey: ['posts', page],
* queryFn: () => fetchPosts(page),
* placeholderData: keepPreviousData,
* })
*
* if (isError) return <span>Error: {error.message}</span>
*
* return (
* <div>
* <ul>
* {data?.map((post) => <li key={post.id}>{post.title}</li>)}
* </ul>
* <button
* disabled={isPlaceholderData}
* onClick={() => setPage((old) => old + 1)}
* >
* Next Page
* </button>
* </div>
* )
* }
* ```
*/
export function useQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): UseQueryResult<TData, TError>
export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
return useBaseQuery(options, QueryObserver, queryClient)
}
+137
View File
@@ -0,0 +1,137 @@
'use client'
import { InfiniteQueryObserver, skipToken } from '@tanstack/query-core'
import { useBaseQuery } from './useBaseQuery'
import { defaultThrowOnError } from './suspense'
import type {
DefaultError,
InfiniteData,
InfiniteQueryObserverSuccessResult,
QueryClient,
QueryKey,
QueryObserver,
} from '@tanstack/query-core'
import type {
UseSuspenseInfiniteQueryOptions,
UseSuspenseInfiniteQueryResult,
} from './types'
/**
* The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError`,
* `enabled`, and `placeholderData`.
*
* Caveat: cancellation does not work.
*
* @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request
* waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until
* then. There's no way to parallelize multiple infinite queries under Suspense. Also 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 useInfiniteQuery} for the non-Suspense version of this hook.
* @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined,
* `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set
* accordingly).
*
* @example
* The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
* required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
* Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseInfiniteQuery,
* } from '@tanstack/react-query'
*
* function Projects() {
* // `data` is guaranteed to be defined here — no `isPending` check needed.
* const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
* useSuspenseInfiniteQuery({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* return (
* <div>
* <ul>
* {data.pages.map((page) =>
* page.projects.map((project) => <li key={project.id}>{project.name}</li>),
* )}
* </ul>
* <button
* onClick={() => fetchNextPage()}
* disabled={!hasNextPage || isFetching}
* >
* {isFetchingNextPage
* ? 'Loading more...'
* : hasNextPage
* ? 'Load More'
* : 'Nothing more to load'}
* </button>
* </div>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading projects...</h1>}>
* <Projects />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
export function useSuspenseInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UseSuspenseInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
queryClient?: QueryClient,
): UseSuspenseInfiniteQueryResult<TData, TError> {
if (process.env.NODE_ENV !== 'production') {
if ((options.queryFn as any) === skipToken) {
console.error('skipToken is not allowed for useSuspenseInfiniteQuery')
}
}
return useBaseQuery(
{
...options,
enabled: true,
suspense: true,
throwOnError: defaultThrowOnError,
placeholderData: undefined,
},
InfiniteQueryObserver as typeof QueryObserver,
queryClient,
) as InfiniteQueryObserverSuccessResult<TData, TError>
}
+529
View File
@@ -0,0 +1,529 @@
'use client'
import { skipToken } from '@tanstack/query-core'
import { useQueries } from './useQueries'
import { defaultThrowOnError } from './suspense'
import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
import type {
DefaultError,
QueryClient,
QueryFunction,
ThrowOnError,
} from '@tanstack/query-core'
// Avoid TS depth-limit error in case of large array literal
type MAXIMUM_DEPTH = 20
// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
type SkipTokenForUseQueries = symbol
type GetUseSuspenseQueryOptions<T> =
// Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
T extends {
queryFnData: infer TQueryFnData
error?: infer TError
data: infer TData
}
? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? UseSuspenseQueryOptions<TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? UseSuspenseQueryOptions<unknown, TError, TData>
: // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
T extends [infer TQueryFnData, infer TError, infer TData]
? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
: T extends [infer TQueryFnData, infer TError]
? UseSuspenseQueryOptions<TQueryFnData, TError>
: T extends [infer TQueryFnData]
? UseSuspenseQueryOptions<TQueryFnData>
: // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, infer TQueryKey>
| SkipTokenForUseQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? UseSuspenseQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>
: T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, infer TQueryKey>
| SkipTokenForUseQueries
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? UseSuspenseQueryOptions<
TQueryFnData,
TError,
TQueryFnData,
TQueryKey
>
: // Fallback
UseSuspenseQueryOptions
type GetUseSuspenseQueryResult<T> =
// Part 1: responsible for mapping explicit type parameter to function result, if object
T extends { queryFnData: any; error?: infer TError; data: infer TData }
? UseSuspenseQueryResult<TData, TError>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? UseSuspenseQueryResult<TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? UseSuspenseQueryResult<TData, TError>
: // Part 2: responsible for mapping explicit type parameter to function result, if tuple
T extends [any, infer TError, infer TData]
? UseSuspenseQueryResult<TData, TError>
: T extends [infer TQueryFnData, infer TError]
? UseSuspenseQueryResult<TQueryFnData, TError>
: T extends [infer TQueryFnData]
? UseSuspenseQueryResult<TQueryFnData>
: // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, any>
| SkipTokenForUseQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? UseSuspenseQueryResult<
unknown extends TData ? TQueryFnData : TData,
unknown extends TError ? DefaultError : TError
>
: T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, any>
| SkipTokenForUseQueries
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? UseSuspenseQueryResult<
TQueryFnData,
unknown extends TError ? DefaultError : TError
>
: // Fallback
UseSuspenseQueryResult
/**
* The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every
* entry's `queryFn`/`select` are inferred individually, up to 20 elements. An opaque array (e.g. `unknown[]`)
* is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls back to a
* single homogeneous {@link UseSuspenseQueryOptions} type.
*
* @template T - The type of the `queries` array as written at the call site.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant
* to be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
export type SuspenseQueriesOptions<
T extends Array<any>,
TResults extends Array<any> = [],
TDepth extends ReadonlyArray<number> = [],
> = TDepth['length'] extends MAXIMUM_DEPTH
? Array<UseSuspenseQueryOptions>
: T extends []
? []
: T extends [infer Head]
? [...TResults, GetUseSuspenseQueryOptions<Head>]
: T extends [infer Head, ...infer Tails]
? SuspenseQueriesOptions<
[...Tails],
[...TResults, GetUseSuspenseQueryOptions<Head>],
[...TDepth, 1]
>
: Array<unknown> extends T
? T
: // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
// use this to infer the param types in the case of Array.map() argument
T extends Array<
UseSuspenseQueryOptions<
infer TQueryFnData,
infer TError,
infer TData,
infer TQueryKey
>
>
? Array<
UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>
>
: // Fallback
Array<UseSuspenseQueryOptions>
/**
* The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors
* {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements.
* A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20
* elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type.
*
* @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant
* to be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
export type SuspenseQueriesResults<
T extends Array<any>,
TResults extends Array<any> = [],
TDepth extends ReadonlyArray<number> = [],
> = TDepth['length'] extends MAXIMUM_DEPTH
? Array<UseSuspenseQueryResult>
: T extends []
? []
: T extends [infer Head]
? [...TResults, GetUseSuspenseQueryResult<Head>]
: T extends [infer Head, ...infer Tails]
? SuspenseQueriesResults<
[...Tails],
[...TResults, GetUseSuspenseQueryResult<Head>],
[...TDepth, 1]
>
: { [K in keyof T]: GetUseSuspenseQueryResult<T[K]> }
/**
* The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
* option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
*
* @param options - The `queries` array to run in Suspense, and an optional `combine` function.
* @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
* will be used.
* @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
* defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
* flags set accordingly).
*
* Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
* stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
* this, make sure to set a high enough `staleTime`. Cancellation does not work.
*
* @example
* The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
* required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
* Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseQueries,
* } from '@tanstack/react-query'
*
* function Posts({ ids }: { ids: Array<number> }) {
* // Every result is guaranteed to be defined — no per-query `isPending` check needed.
* const postQueries = useSuspenseQueries({
* queries: ids.map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })),
* })
*
* return (
* <ul>
* {postQueries.map((query) => (
* <li key={query.data.id}>{query.data.title}</li>
* ))}
* </ul>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading posts...</h1>}>
* <Posts ids={[1, 2, 3]} />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*
* @example
* Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
* they fetch in parallel rather than suspending one after another:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseQueries,
* } from '@tanstack/react-query'
*
* function Dashboard() {
* const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
* queries: [
* { queryKey: ['users'], queryFn: fetchUsers },
* { queryKey: ['teams'], queryFn: fetchTeams },
* { queryKey: ['projects'], queryFn: fetchProjects },
* ],
* })
*
* return (
* <div>
* <UserList users={usersQuery.data} />
* <TeamList teams={teamsQuery.data} />
* <ProjectList projects={projectsQuery.data} />
* </div>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading dashboard...</h1>}>
* <Dashboard />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*
* @example
* `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes,
* not on every individual query update. This overload is the only one that accepts `combine`:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseQueries,
* } from '@tanstack/react-query'
*
* function Refresh() {
* const anyFetching = useSuspenseQueries({
* queries: [
* { queryKey: ['users'], queryFn: fetchUsers },
* { queryKey: ['teams'], queryFn: fetchTeams },
* ],
* combine: (results) => results.some((result) => result.isFetching),
* })
*
* return anyFetching ? <span>Refreshing…</span> : null
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading dashboard...</h1>}>
* <Refresh />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
export function useSuspenseQueries<
T extends Array<any>,
TCombinedResult = SuspenseQueriesResults<T>,
>(
options: {
/**
* An array with query option objects identical to `useSuspenseQuery`.
*/
queries:
| readonly [...SuspenseQueriesOptions<T>]
| readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions<T[K]> }]
/**
* Use this to combine the results of the queries into a single value. The result will be structurally
* shared to be as referentially stable as possible.
*/
combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
},
queryClient?: QueryClient,
): TCombinedResult
/**
* The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
* option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
*
* @param options - The `queries` array to run in Suspense, and an optional `combine` function.
* @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
* will be used.
* @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
* defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
* flags set accordingly).
*
* Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
* stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
* this, make sure to set a high enough `staleTime`. Cancellation does not work.
*
* @example
* The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
* required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
* Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseQueries,
* } from '@tanstack/react-query'
*
* function Posts({ ids }: { ids: Array<number> }) {
* // Every result is guaranteed to be defined — no per-query `isPending` check needed.
* const postQueries = useSuspenseQueries({
* queries: ids.map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })),
* })
*
* return (
* <ul>
* {postQueries.map((query) => (
* <li key={query.data.id}>{query.data.title}</li>
* ))}
* </ul>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading posts...</h1>}>
* <Posts ids={[1, 2, 3]} />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*
* @example
* Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
* they fetch in parallel rather than suspending one after another:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import {
* QueryErrorResetBoundary,
* useSuspenseQueries,
* } from '@tanstack/react-query'
*
* function Dashboard() {
* const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
* queries: [
* { queryKey: ['users'], queryFn: fetchUsers },
* { queryKey: ['teams'], queryFn: fetchTeams },
* { queryKey: ['projects'], queryFn: fetchProjects },
* ],
* })
*
* return (
* <div>
* <UserList users={usersQuery.data} />
* <TeamList teams={teamsQuery.data} />
* <ProjectList projects={projectsQuery.data} />
* </div>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading dashboard...</h1>}>
* <Dashboard />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
export function useSuspenseQueries<
T extends Array<any>,
TCombinedResult = SuspenseQueriesResults<T>,
>(
options: {
/**
* An array with query option objects identical to `useSuspenseQuery`.
*/
queries: readonly [...SuspenseQueriesOptions<T>]
/**
* Use this to combine the results of the queries into a single value. The result will be structurally
* shared to be as referentially stable as possible.
*/
combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
},
queryClient?: QueryClient,
): TCombinedResult
export function useSuspenseQueries(options: any, queryClient?: QueryClient) {
return useQueries(
{
...options,
queries: options.queries.map((query: any) => {
if (process.env.NODE_ENV !== 'production') {
if (query.queryFn === skipToken) {
console.error('skipToken is not allowed for useSuspenseQueries')
}
}
return {
...query,
suspense: true,
throwOnError: defaultThrowOnError,
enabled: true,
placeholderData: undefined,
}
}),
},
queryClient,
)
}
+101
View File
@@ -0,0 +1,101 @@
'use client'
import { QueryObserver, skipToken } from '@tanstack/query-core'
import { useBaseQuery } from './useBaseQuery'
import { defaultThrowOnError } from './suspense'
import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
/**
* The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and
* `placeholderData` — and `queryFn` may not be `skipToken`, since Suspense hooks can't render a "disabled" state.
*
* Caveat: cancellation does not work.
*
* @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request
* waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then.
* Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they
* fetch in parallel.
* @param options - The {@link UseSuspenseQueryOptions} to use — the same options as `useQuery`, minus the ones listed above.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
* be used.
* @returns The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData`
* is missing, and `status` is either `success` or `error` (with the derived flags set accordingly).
*
* @example
* The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is
* required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
* Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
* ```tsx
* import { Suspense } from 'react'
* import { ErrorBoundary } from 'react-error-boundary'
* import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query'
*
* function Posts() {
* // `data` is guaranteed to be defined here — no `isPending` check needed.
* const { data, isFetching } = useSuspenseQuery({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* })
*
* return (
* <div>
* <h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
* <ul>
* {data.map((post) => (
* <li key={post.id}>{post.title}</li>
* ))}
* </ul>
* </div>
* )
* }
*
* function App() {
* return (
* <QueryErrorResetBoundary>
* {({ reset }) => (
* <ErrorBoundary
* onReset={reset}
* fallbackRender={({ resetErrorBoundary }) => (
* <div>
* There was an error!
* <button onClick={() => resetErrorBoundary()}>Try again</button>
* </div>
* )}
* >
* <Suspense fallback={<h1>Loading posts...</h1>}>
* <Posts />
* </Suspense>
* </ErrorBoundary>
* )}
* </QueryErrorResetBoundary>
* )
* }
* ```
*/
export function useSuspenseQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): UseSuspenseQueryResult<TData, TError> {
if (process.env.NODE_ENV !== 'production') {
if ((options.queryFn as any) === skipToken) {
console.error('skipToken is not allowed for useSuspenseQuery')
}
}
return useBaseQuery(
{
...options,
enabled: true,
suspense: true,
throwOnError: defaultThrowOnError,
placeholderData: undefined,
},
QueryObserver,
queryClient,
) as UseSuspenseQueryResult<TData, TError>
}