How to chain useQuery calls? | Use result from one query as input for another?

How can I achieve something like this?
14 Replies
barry
barry2y ago
function Example() {
const { data: firstQuery } = trpc.example.someQuery.useQuery();
const { data: secondQuery } = trpc.example.someQuery.useQuery({
id: firstQuery.data.ids
}, {
enabled: !!firstQuery?.ids
});

return (...)
}
function Example() {
const { data: firstQuery } = trpc.example.someQuery.useQuery();
const { data: secondQuery } = trpc.example.someQuery.useQuery({
id: firstQuery.data.ids
}, {
enabled: !!firstQuery?.ids
});

return (...)
}
But, you could probably make your backend handle this instead of doing 2 queries.
cje
cje2y ago
yea, chances are you want this to be one query that makes two database requests round trips are expensive
Dari
Dari2y ago
Of course, but in my specific case i am mapping the first query with data that is only available client and i don't want it to be passed to the server
barry
barry2y ago
So the second query takes in information that the backend should not have?
Dari
Dari2y ago
Im still running into an issue, tho:
trpc.example.someQuery.useQuery({
ids: firstQuery.data!.ids // data is undefined ! didn't work
}, {
enabled: !!firstQuery.data?.ids
});
trpc.example.someQuery.useQuery({
ids: firstQuery.data!.ids // data is undefined ! didn't work
}, {
enabled: !!firstQuery.data?.ids
});
yup
barry
barry2y ago
Of course it's undefined if you destructured it Just use the ? operator btw
Dari
Dari2y ago
Not working, because ids cant be undefined / null
barry
barry2y ago
And it's firstQuery?.ids, there is no data property if you copied my code
Dari
Dari2y ago
no i didn't destruct it
barry
barry2y ago
👍 Just gotta tell TypeScript to shut up then
Dari
Dari2y ago
but it leads to a runtime error
barry
barry2y ago
What if you pass a default that fits the requirements
Dari
Dari2y ago
never mind sorry you are absolutely right with ? it worked and it's just typescript complaining Thank you very much
barry
barry2y ago
No worries
Want results from more Discord servers?
Add your server