TanStackT
TanStack3mo ago
7 replies
primary-violet

How to prefetch in server component inside next 16.0.1

Hello I have this server component
import {
  QueryClient,
  HydrationBoundary,
  dehydrate,
} from '@tanstack/react-query';
import { EventsList } from './EventsList';
import { getEvents } from '@/lib/actions/polymarket';
import { LIMIT } from '@/lib/constants';

export async function EventsWrapper() {
  // Fetch the data directly on the server FIRST (before any time operations)
  // This satisfies the Cache Component requirement of accessing data before Date.now()
  let initialData = null;
  let error = null;

  try {
    initialData = await getEvents(LIMIT, 0);
  } catch (err) {
    error = err;
    console.error('Server-side fetch failed:', err);
  }

  // NOW create QueryClient after data fetch
  const queryClient = new QueryClient();

  if (initialData) {
    // Set the initial data in the query cache
    queryClient.setQueryData(['events', { limit: LIMIT }], {
      pages: [initialData],
      pageParams: [0],
    });
  }

  const dehydratedState = dehydrate(queryClient);

  return (
    <HydrationBoundary state={dehydratedState}>
      <EventsList />
    </HydrationBoundary>
  );
}


which is wrapped in suspense inside page.tsx

i'm trying to prefetch data build time, feed the query and then my components consume it, problem is i see those errors

rror: Route "/" used `Date.now()` before accessing either uncached data (e.g. `fetch()`) or Request data (e.g. `cookies()`, `headers()`, `connection()`, and `searchParams`). Accessing the current time in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time
    at EventsWrapper (app/(home)/components/EventsWrapper.tsx:28:17)
    at Home (app/(home)/page.tsx:17:11)
  27 |   if (initialData) {
> 28 |     queryClient.setQueryData(['events', { limit: LIMIT }], {
     |                 ^
Was this page helpful?