I need a bit of help understanding trpc

I've got everything set up as per the next-auth starter. I've got a query that gets me an index of things with ids, and then I need to loop over those things and use each id and call another query per item. Finally I want to make a state of { thingWithId, ListofThings } I can't find a way to do this: useQueries doesn't work because the number of hooks can change. I can't figure out how to do query api.mything inside useEffect because my client only seems to have the useQuery hook which can't be used inside useEffect. What do I have to do here? Do I need two clients? Is there an option I've missed to give me api.query? Halp 🙂
5 Replies
barry
barry•2y ago
Well you're best off handling all this on the server, but you can just make a component that takes an id and does the rest? if you do it this way you end up with a waterfall
Client requests id's
Client requests more stuff based on id's
Client requests id's
Client requests more stuff based on id's
n + 1 http requests, very not smart Vs
Client requests all of it
Client requests all of it
1 http request, smart
Sean Cassiere
Sean Cassiere•2y ago
The useQuery hook shouldn't be called inside of a useEffect. If you want to called the subsequent requests on the client, you could moove that logic into a child component.
export const Comp = () => {
const { data: posts } = api.posts.getAll.useQuery()
return <div>
{(posts ?? []).map(post => <SubComp key={post.id} postId={post.id} />)}
</div>
}

const SubComp = ({ postId }: { postId: string }) => {
const { data: post } = api.posts.getById.useQuery({ id: postId })

return <div>id: {post?.id}</div>
}
export const Comp = () => {
const { data: posts } = api.posts.getAll.useQuery()
return <div>
{(posts ?? []).map(post => <SubComp key={post.id} postId={post.id} />)}
</div>
}

const SubComp = ({ postId }: { postId: string }) => {
const { data: post } = api.posts.getById.useQuery({ id: postId })

return <div>id: {post?.id}</div>
}
cdodev
cdodev•2y ago
Yeah I definitely want to avoid that - but I have to call the api that gives me that data on the server instead (chargebee doesn't seem to have realised that people might want to know these things at the same time). It would make more sense to do this server side in one go I suppose. But out of interest - how could I do this from the client?
barry
barry•2y ago
Sean just showed you how
cdodev
cdodev•2y ago
I've been in Haskell land too long I can't function without Monad and Applicative any more!
Want results from more Discord servers?
Add your server