Repository navigation
Replies: 1 comment
|
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, |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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