Best practices for modeling "conditional" queries
What's the best practice for modeling queries that rely on other queries.
12 Replies
Hey @Chad Maycumber
There's a couple options here, based on how you might want to model your components.
1. Nest a separate component to load the separate query. e.g.
{selectedAI && <Conversation chatId={selectedId} />}
where the Conversation
component calls useQuery("ai:conversationsBetweenUser")
2. If you'd like to keep both queries in one component, you could refactor the conversationsBetweenUser
function to have the id
arg be optional and return a loading value (like undefined
) if id
is not setIf I have two separate components that rely on useQuery("ai:conversationsBetweenUser") will it make two requests? t
If both
useQuery
hooks have the same arguments, it will be one request. The Convex client caches results (and subscribes to updates) based on the arguments until the last hook referencing those arguments is unmountedThere is also a
useQueries
hook where you can dynamically pick which queries to run - you could put only one in there, and include the other conditionally when you have the selectedId
And stay tuned! We're going to add an
enabled
option to useQuery
to solve this very soon...This would be 🔥
Thank you all for the help 🙏
Quick question on the
useQueries
approach, will this for my ais:list
query to re-query if the selectedId changes?Just the second query! And you can use
useQueries
to do 1 query if you have an ID and 0 if you don't have anyI came back to this and here's what I'm doing. But react is giving me a too many renders error. Do you all have docs on this?
Sorry no detailed docs on this yet 😞 . Wanna try moving the argument to
useQueries
into a useMemo
call? I suspect there is something circular going on where each render recreates the queries object which triggers another render.
But this thread has inspired me to work on just getting enabled
in soon. Should be in Convex 0.14.0 or 0.15.0Sounds great! Really looking forward to that!
Any timeline for this? Maybe convex v16? 🙏
We'll probably have something for this in the next few weeks, probably not v16. We've been holding back to make sure the API we provide for this will compose well with all the different ways folks use Convex, in particular custom React hooks.
Gotcha makes sense looking forward to it