Repository navigation
Replies: 4 comments 5 replies
|
You don't need a custom generic wrapper for this. Just define the base factory with a required id, then make a small wrapper for the skippable use case: const todoOptions = (id: string) =>
queryOptions({
queryKey: ['todo', id],
queryFn: () => fetchTodo(id),
});
const skippableTodoOptions = (id?: string) =>
id ? todoOptions(id) : queryOptions({ queryKey: ['todo', id], queryFn: skipToken });That keeps the key and queryFn together in one spot. In components where the id is present, |
|
To make a single Here is the pattern: import { queryOptions, skipToken, type UseQueryOptions, type UseSuspenseQueryOptions } from '@tanstack/react-query';
// Overload 1: When id is defined, queryFn returns Promise<Todo>, compatible with useSuspenseQuery
export function todoOptions(id: string): ReturnType<typeof queryOptions<{
queryKey: ['todo', string];
queryFn: () => Promise<Todo>;
}>>;
// Overload 2: When id may be undefined, queryFn can be skipToken, compatible with useQuery
export function todoOptions(id?: string): ReturnType<typeof queryOptions<{
queryKey: ['todo', string | undefined];
queryFn: typeof skipToken | (() => Promise<Todo>);
}>>;
// Implementation
export function todoOptions(id?: string) {
return queryOptions({
queryKey: ['todo', id],
queryFn: id ? () => fetchTodo(id) : skipToken,
});
}Why This Works
|
|
Put the overloads in one shared builder and infer their return types from import { queryOptions, skipToken, type DefaultError, type QueryKey } from '@tanstack/react-query'
function byOptionalId<TId extends string, TData, const TKey extends QueryKey>(
key: (id: TId | undefined) => TKey,
fetch: (id: TId) => Promise<TData>,
) {
const ready = (id: TId) =>
queryOptions({ queryKey: key(id), queryFn: () => fetch(id) })
const disabled = () =>
queryOptions<TData, DefaultError, TData, TKey>({
queryKey: key(undefined),
queryFn: skipToken,
})
function options(id: TId): ReturnType<typeof ready>
function options(id?: TId): ReturnType<typeof ready> | ReturnType<typeof disabled>
function options(id?: TId) {
return id === undefined ? disabled() : ready(id)
}
return options
}
const todoOptions = byOptionalId((id) => ['todo', id] as const, fetchTodo)
useQuery(todoOptions(maybeId))
useSuspenseQuery(todoOptions(id))
// @ts-expect-error A possibly undefined ID can return the skipped branch.
useSuspenseQuery(todoOptions(maybeId))The type parameters on |
|
The in-factory options can't get simpler than what you have, because You can skip that by moving the check to the call site. The factories stay exactly as they are, and one helper takes a factory plus its arguments, accepting only arguments that are already non-nullable: import { skipToken, type SkipToken } from '@tanstack/react-query'
type Defined<T> = { [K in keyof T]-?: NonNullable<T[K]> }
export function ready<TArgs extends unknown[], TOptions extends { queryFn?: unknown }>(
factory: (...args: TArgs) => TOptions,
...args: Defined<TArgs>
) {
const options = factory(...(args as TArgs))
if (options.queryFn === skipToken) {
throw new Error(`${factory.name || 'queryOptions factory'} returned skipToken for defined arguments`)
}
return options as Omit<TOptions, 'queryFn'> & {
queryFn?: Exclude<TOptions['queryFn'], SkipToken>
}
}// todoOptions is your original factory, unchanged
useQuery(todoOptions(maybeId)) // ✅ data: Todo | undefined
useSuspenseQuery(ready(todoOptions, id)) // ✅ data: Todo
useSuspenseQuery(ready(todoOptions, maybeId)) // ❌ 'string | undefined' is not assignable to 'string'
useSuspenseQuery(ready(todoOptions)) // ❌ Expected 2 arguments, but got 1
// several optional args work the same way
useSuspenseQuery(ready(commentOptions, todoId, commentId))
The trade-off against your helper: call sites read Type-checked under |
Uh oh!
There was an error while loading. Please reload this page.
We define one
queryOptionsfactory per query soqueryKeyandqueryFnlive in exactly one place. Many of them take an id that can be missing, so we useskipToken:Rejecting this in
useSuspenseQueryis right whenidmay be undefined. But the same factory is also rejected in a component that only renders once the id exists (the composition approach from #6206):The type of
queryFncomes from the factory's parameter type, not from the value the caller passes, soqueryOptionsalways picks theUndefinedInitialDataOptionsoverload.What we've considered
todoOptions+todoSuspenseOptions).queryKeyandqueryFnare then duplicated. If they drift apart, the two hooks read different cache entries and invalidation silently misses one.queryOptionsdoes (UnusedSkipTokenOptions/UndefinedInitialDataOptions). This works, but it adds ~10 lines of return types per factory that restateDataTagand the option generics. We have 100+ factories that useskipToken.What we're doing instead
A helper that takes the query's dependencies. It uses
skipTokenwhile any dependency is nullish and picks the return type from the dependencies' types:Each nullable argument gets its own generic, so a defined value at the call site is preserved:
Full TS playground
Questions
skipTokenfactory that's accepted byuseSuspenseQuerywhen the input is known to be defined?skipTokendocs? We'd be happy to open a docs PR.Originally asked in #9445, but that thread is about the opposite problem, so I'm moving it to its own topic.
All reactions