TanStackT
TanStack8mo ago
3 replies
endless-jade

Fetching multiple resources in Loader using ensureQueryData

I had a question about handling multiple data fetches in a loader using ensureQueryData. I followed the example from the docs and added another
queryOptions
for a second fetch. Is this the recommended approach?

// src/routes/posts.tsx

const postsQueryOptions = queryOptions({
  queryKey: ['posts'],
  queryFn: () => fetchPosts(),
})

const userQueryOptions = queryOptions({
  queryKey: ['user'],
  queryFn: () => fetchUser(),
})

export const Route = createFileRoute({
  loader: async () => {
    await Promise.all([
      queryClient.ensureQueryData(postsQueryOptions),
      queryClient.ensureQueryData(userQueryOptions),
    ])
  },
  component: () => {
    const { data: posts } = useSuspenseQuery(postsQueryOptions)
    const { data: user } = useSuspenseQuery(userQueryOptions)

    return (
      <div>
        {posts.map((post) => (
          <Post key={post.id} post={post} />
        ))}
      </div>
    )
  },
})
Was this page helpful?