T
TanStackβ€’3y ago
fair-rose

typescript parallel useQuery/useInfiniteQuery type guard for data?

Hey there! Is there a way/best practice to type guard multiple queries w/o using useQueries? I have a page that has a handful of mixed queries (regular and infinite) and what i would like to do is guarantee all have data before displaying anything. It's easily accomplished with a if
if (query1.data && query2.data && query3.data) {
/* JSX W/ DATA GUARANTEED */
}
if (query1.data && query2.data && query3.data) {
/* JSX W/ DATA GUARANTEED */
}
but that gets unwieldy quick with more than a few queries. Extracting all that to a local var didn't do the trick since typescript only knows the var is "true" not that each data is defined. Any thoughts/recs from y'all? Thanks!
6 Replies
fascinating-indigo
fascinating-indigoβ€’3y ago
Extracting all that to a local var didn't do the trick since typescript only knows the var is "true" not that each data is defined
What do you mean by this? This would achieve the same thing?
const allHere = !!query1.data && !!query2.data && !!query3.data;
const allHere = !!query1.data && !!query2.data && !!query3.data;
Also, if some queries are tightly coupled (always need one another to function), you can combine them in one and fetch both inside the queryFn: https://twitter.com/Julien_Delort/status/1628777914291392513
Julien Delort (@Julien_Delort)
@tan_stack query tip: when 2 endpoints are tightly coupled and you always need to call them both to get the data, you don't necessarily need multiple useQuery calls: #javascript #webdev #code #webdevelopment #programming #reactjs #react
From Julien Delort (@Julien_Delort)
Twitter
eastern-cyan
eastern-cyanβ€’3y ago
This condition (even if the expression is stored in a variable) should narrow the type of the query data, assuming you're conditionally rendering using it. Is this not the case? I think it should be
fair-rose
fair-roseOPβ€’3y ago
so bizarre - i swear I did that @julien/ @Louis and it didn't narrow. Just double checked and it does. πŸ€¦πŸ»β€β™‚οΈ . Chalk that up to too long a day hahah.
eastern-cyan
eastern-cyanβ€’3y ago
Glad it's sorted πŸŽ‰ :reactquery:
fair-rose
fair-roseOPβ€’3y ago
@julien @Louis oh wow - i was hitting this narrowing problem again and realized what i was doing that was different from @julien suggestion and resulting in not narrowing - Boolean(query1.data) && Boolean(query2.data) as opposed to the !!. Just figured I'd follow up in case anyone else thought the two ways would behave identically. πŸ€·πŸ»β€β™‚οΈ
eastern-cyan
eastern-cyanβ€’3y ago
That’s odd! Thanks for the update

Did you find this page helpful?