How to load more than one external resource in loader with React Query?
Hi There!
I'm trying to find out how to load more than one resource from the backend for one route, with Tanstack Query and unfortunately they do depend on each other.
Here is the example code from the docs for using Query, but I really could not find any way to have more than one query depending on each other before the route is rendered.
Could somebody point me in the right direction? Thanks!
I was thinking to use Promise.all() in the loader function, but how can i start the second query with data (an ID) from the first one? Or should I just chain the promises?
// src/routes/posts.tsx
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})
export const Route = createFileRoute('/posts')({
// Use the
loader option to ensure that the data is loaded
//What to do here to have multiple depending queries? Promise.all()?
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const {
data: { posts },
} = useSuspenseQuery(postsQueryOptions)
return (
<div>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
)
},
})
2 Replies
wise-white•2mo ago
IMO, Promise.all is the way to go if you can load your data independently. but in the case where you have data that's dependent on previous data, you'll have to chain them ðŸ«
sensitive-blueOP•2mo ago
Thanks! 🙂