TanStackT
TanStack16mo ago
4 replies
popular-magenta

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>
  );
}


It appears to work however I noticed that
react-query
doesn't appear to track the
tags
query and it is marked as inactive
StackBlitzMichael Wolfenden
Run official live example code for Router Basic React Query File Based, created by Tanstack on StackBlitz
Router Basic React Query File Based Example (forked) - StackBlitz
Was this page helpful?