if you want to use a query where the data is guaranted to resolve before it is returned to you and it can't undefined, there is another hook called useSuspenseQuery.
import {useSuspenseQuery} from "@tanstack/react-query"
import {getProducts} from "@/services/get-products"
export async function Products({products}){
await {data}= useSuspenseQuery({
queryKey:["products"],
queryFn:getProducts,
initialData:products
})
return(
<div>
{data.map(product=>(
<div>
<h2>{[product.name](<http://product.name/>)}</h2>
</div>
)) }
</div>
)
return(
<Suspense fallback={<h1>Loading...</h1>}> <Products></suspense>
)
}
Multiple queries: we have multiple queries that are all completely independent of each other. There is a utility function from React Query that allows us to execute all of our queries together without having to call each one separately. syntax: const [query1, query2, query3] = useQueries({queries:[{},{},{}]}) const [{data:firstQueryData, isPending:firstQueryIsPending}, query2, query3] = useQueries({queries:[{},{},{}]})
const useBookDetails(bookId){
return useQueries({
queries:[{
queryKey: ["book", bookId],
queryFn:()=> getBook(bookId)
},
{
queryKey: ["reviews", bookId],
queryFn:()=> getReviwes(bookId)
}],
combine:(queries)=>{
const isPending = queries.some(query=> query.status === "pending")
const isError = queries.some(query=> query.status === "error")
const [book, reviews] = queries.map(query=> query.data)
return{
isPending,
isError
book,
reviews
}
}
)}
}
Note: You can also use the useSuspenseQueries hook.