How to do infinite query with route loader? #3855
-
I have a page where I want to show a list of users with infinite scrolling. I am not doing SSR, instead I have a traditional client that fetches data from a 3rd party API. I do not want the page to render until some of the users have been fetched, in order to reduce CLS. Then, as the user scrolls through the data, it should fetch more on demand. I am using the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Use import { infiniteQueryOptions, useSuspenseInfiniteQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
const options = infiniteQueryOptions({
queryKey: ["posts"],
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextPage,
queryFn: fetchPosts,
});
export const Route = createFileRoute("/dashboard/")({
loader: ({ context }) => {
await context.queryClient.prefetchInfiniteQuery(options);
},
component: RouteComponent,
});
function RouteComponent() {
const query = useSuspenseInfiniteQuery(options);
return <div>Hello "/dashboard"!</div>;
} |
Beta Was this translation helpful? Give feedback.
Use
infiniteQueryOptions
to share the query logic betweenuseSuspenseInfiniteQuery
(in the component) andqueryClient.prefetchInfiniteQuery
(in the loader):