How to perform 2 trpc queries, when I need the second query to rely on data from the first?

Sorry for making the title so complex What I need is simple. I need to make 2 requests but get some data from the first before making the second one. This is my code which fails to work:
const { data: profile } = api.user.whoami.useQuery(); const { data: company } = api.company.getById.useQuery({ id: profile.companyId });
11 Replies
Josh
Josh11mo ago
make another trpc route such that you only need one procedure
Dor
Dor11mo ago
Yeah, I can do that. I can also include the company data in the "whoami" route. But I was wodnering, for sake of learning, how this would be possible
Josh
Josh11mo ago
you would have to disable the second query until the first one has the data, but this is a terrible pattern that is hard to do for a reason; it's not good
Dor
Dor11mo ago
Ok so that was my initial thought I guess I just needed this validation Thank you! deranged
Josh
Josh11mo ago
yur another way to do it that may be a bit more elegant is to put the second query in a child component of the node that your first query lives, pass the data from the first query to the new child component & only render the child component when the data exists/ is has been fetched then you're second query will always have the data it needs since the component it lives in is only rendered when it has the data needed to do the fetch this would only make sense to do if you can render out part of your page with data from your first query, then the rest of your page in the child component if you need the data from both to render anything, definitely just make a whole new route
Dor
Dor11mo ago
Interesting.. In my current case I need the data to appear at once but I get where making a component might work and when to separate the routes
Rhys
Rhys11mo ago
React query should have a skip option which you can set to true if profile is undefined
Rhys
Rhys11mo ago
Disabling/Pausing Queries | TanStack Query Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option. When enabled is false:
Dor
Dor11mo ago
Uuuu that's super cool, is it supported in tRPC?
Rhys
Rhys11mo ago
tRPC uses react query so yeah There’s an age old saying “if you have a tRPC question it’s probably a react query question”
Dor
Dor11mo ago
Right right, I meant more like if its covered in the docs tRPC docs is my go-to even though it uses react query Gonna give it a try Lol it worked, I like it! Think I'll keep this solution for now But surely good to be aware of 3 different solutions Thanks guys!
Want results from more Discord servers?
Add your server