TanStackT
TanStackโ€ข11mo agoโ€ข
1 reply
popular-magenta

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


// 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...
Was this page helpful?