Best practices for modeling "conditional" queries

What's the best practice for modeling queries that rely on other queries.
No description
12 Replies
ari
ari2y ago
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 set
Chad Maycumber
Chad MaycumberOP2y ago
If I have two separate components that rely on useQuery("ai:conversationsBetweenUser") will it make two requests? t
ari
ari2y ago
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 unmounted
ian
ian2y ago
There 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
alexcole
alexcole2y ago
And stay tuned! We're going to add an enabled option to useQuery to solve this very soon...
Chad Maycumber
Chad MaycumberOP2y ago
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?
alexcole
alexcole2y ago
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 any
Chad Maycumber
Chad MaycumberOP2y ago
I 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?
No description
alexcole
alexcole2y ago
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.0
Chad Maycumber
Chad MaycumberOP2y ago
Sounds great! Really looking forward to that! Any timeline for this? Maybe convex v16? 🙏
ballingt
ballingt2y ago
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.
Chad Maycumber
Chad MaycumberOP2y ago
Gotcha makes sense looking forward to it

Did you find this page helpful?