T
TanStack11mo ago
ratty-blush

RQ architecture suggestions

I'm having a bit of a dillema on how to structure my queries. I really love using queryOptions as it lets me override any of the options.
export const getProjectQueryOpts = (
variables: GetProjectRequest,
init: RequestInit = {},
) => {
const queryKey = [
"projects",
variables.params.pid
] as const

return queryOptions({
queryKey,
queryFn: () => getProject(variables, init)
});
};
export const getProjectQueryOpts = (
variables: GetProjectRequest,
init: RequestInit = {},
) => {
const queryKey = [
"projects",
variables.params.pid
] as const

return queryOptions({
queryKey,
queryFn: () => getProject(variables, init)
});
};
const project = useQuery({
...getProjectQueryOpts({
params: {
pid
}
}),
staleTime: Infinity,
});
const project = useQuery({
...getProjectQueryOpts({
params: {
pid
}
}),
staleTime: Infinity,
});
The problem with this approach is that you cant effectively use skipToken because I want to keep the variables as required. The only solution is to make the variables optional in which case I can make typescript happy with the usage, and then handle the skipToken within the getProjectQueryOpts - but it feels weird to do so....
5 Replies
rare-sapphire
rare-sapphire11mo ago
Make your getProjectsQueryOpts accept skipToken instead of variables
ratty-blush
ratty-blushOP11mo ago
Smartt!! Didnt even think about that
rare-sapphire
rare-sapphire11mo ago
we have the same abstraction and it works well
...getProjectQueryOpts( pid ? {
params: {
pid
} : skipToken
})
...getProjectQueryOpts( pid ? {
params: {
pid
} : skipToken
})
then forward the skipToken to the queryFn if it's a skipToken
ratty-blush
ratty-blushOP11mo ago
Yep - did exactly that. This is great. Thank you! Oh - I had another question - given this setup, how do you handle queryKey inputs? Do you just do something like this?
export const getProjectQueryOpts = (
variables: GetProjectRequest | SkipToken,
init: RequestInit = {},
) => {
const isSkipToken = variables === skipToken
const queryKey = [
"doc-service",
"projects",
(!isSkipToken && variables.params.pid)
] as const

return queryOptions({
queryKey,
queryFn: !isSkipToken ? () => getProject(variables, init) : skipToken
});
};
export const getProjectQueryOpts = (
variables: GetProjectRequest | SkipToken,
init: RequestInit = {},
) => {
const isSkipToken = variables === skipToken
const queryKey = [
"doc-service",
"projects",
(!isSkipToken && variables.params.pid)
] as const

return queryOptions({
queryKey,
queryFn: !isSkipToken ? () => getProject(variables, init) : skipToken
});
};
rare-sapphire
rare-sapphire11mo ago
no, I always put variables.params.id into the queryKey, even if it's undefined. The queryFn won't run so it doesn't matter

Did you find this page helpful?