T
TanStack9mo ago
genetic-orange

Keeping paginated items in client even when navigate away and back again in Nextjs SSR with prefetch

Hello, I am trying data prefetching and caching inside Nextjs with TanstackQuery. The problem is that when navigate way from the post-page after loading 30 items and come back again, the data is reset to initial 10 items. That is causing frustration right? How can I keep previous paginated data when throw away and come back? Thanks 🙏
// prefetch inside server comopnent
export default async function Posts() {
const queryClient = getQueryClient()

queryClient.prefetchInfiniteQuery({
queryKey: ["posts"],
queryFn: () => getPosts({ limit: 10 }),
initialPageParam: "",
})

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
// prefetch inside server comopnent
export default async function Posts() {
const queryClient = getQueryClient()

queryClient.prefetchInfiniteQuery({
queryKey: ["posts"],
queryFn: () => getPosts({ limit: 10 }),
initialPageParam: "",
})

return (
<HydrationBoundary state={dehydrate(queryClient)}>
<Posts />
</HydrationBoundary>
)
}
// make pagination inside client component
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useSuspenseInfiniteQuery({
queryKey: ["posts"],
queryFn: ({ pageParam }) =>
getActiveMoments({ limit: 10, cursor: pageParam }),
initialPageParam: "",
getNextPageParam: (lastPage) => lastPage.nextCursor,
})


// Render contents...
// make pagination inside client component
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useSuspenseInfiniteQuery({
queryKey: ["posts"],
queryFn: ({ pageParam }) =>
getActiveMoments({ limit: 10, cursor: pageParam }),
initialPageParam: "",
getNextPageParam: (lastPage) => lastPage.nextCursor,
})


// Render contents...
1 Reply
like-gold
like-gold9mo ago
with nextJs's caching; or with implementing caching on the server; or with having the current page cursor in the url and then using the pages: number option on prefetchQuery to prefetch the same amount.

Did you find this page helpful?