T
TanStack12mo ago
multiple-amethyst

combining react query and defer

I have a page that displays articles and tags however I don't want to wait for the tags to load before displaying the articles. Is this the correct way to combine react query , ensureQueryData and defer to achieve this result? The full sandbox is here: https://stackblitz.com/edit/tanstack-router-ezbw75?file=src%2Froutes%2Findex.tsx
export const Route = createFileRoute('/')({
component: Home,
loader: async ({ context: { queryClient } }) => {
await queryClient.ensureQueryData(postsQueryOptions());

return {
tagsPromise: defer(queryClient.ensureQueryData(tagsQueryOptions())),
};
},
});

function Home() {
const { data: posts } = useSuspenseQuery(postsQueryOptions());
const { tagsPromise } = Route.useLoaderData();

return (
<div className="p-2">
<h1>Posts</h1>
<ul>
{posts.map((post) => (<li key={post.id}>{post.title}</li>))}
</ul>
<h1>Tags</h1>
<Suspense fallback={<div>Loading tags...</div>}>
<Await promise={tagsPromise}>{(data) => data.join(', ')}</Await>
</Suspense>
</div>
);
}
export const Route = createFileRoute('/')({
component: Home,
loader: async ({ context: { queryClient } }) => {
await queryClient.ensureQueryData(postsQueryOptions());

return {
tagsPromise: defer(queryClient.ensureQueryData(tagsQueryOptions())),
};
},
});

function Home() {
const { data: posts } = useSuspenseQuery(postsQueryOptions());
const { tagsPromise } = Route.useLoaderData();

return (
<div className="p-2">
<h1>Posts</h1>
<ul>
{posts.map((post) => (<li key={post.id}>{post.title}</li>))}
</ul>
<h1>Tags</h1>
<Suspense fallback={<div>Loading tags...</div>}>
<Await promise={tagsPromise}>{(data) => data.join(', ')}</Await>
</Suspense>
</div>
);
}
It appears to work however I noticed that react-query doesn't appear to track the tags query and it is marked as inactive
Michael Wolfenden
StackBlitz
Router Basic React Query File Based Example (forked) - StackBlitz
Run official live example code for Router Basic React Query File Based, created by Tanstack on StackBlitz
3 Replies
constant-blue
constant-blue12mo ago
you don't need to use defer use call ensureQueryData and then another useSuspenseQuery in the component
multiple-amethyst
multiple-amethystOP12mo ago
@Manuel Schiller doing that will show Loading.... (block the page) until both the articles and tags are loaded
flat-fuchsia
flat-fuchsia12mo ago
Then just call prefetchQueryData and use TanStack Query normally using useQuery.

Did you find this page helpful?