TanStackT
TanStackโ€ข2y agoโ€ข
1 reply
dangerous-fuchsia

Implementing Data Polling with Stale Data in Next.js 14 using React Query

Hey everyone! ๐Ÿ‘‹

Let's delve into a scenario:

In the app I'm developing, there's a flight details page designed to display real-time flight information. The challenge is that this data needs to be updated every few seconds.

Currently, my approach involves a server-side component that initially fetches the data and then passes it down to the flight details component on the client-side. Additionally, there's a loading.tsx component that displays a loading skeleton, as depicted in the images.

Let's review the code below:

// flights/[flightId]/page.tsx

export async function getFlightDetails(
  flightId: string,
): Promise<LiveFlightDetail | null> {
  const url = `${API_BASE_URL}/networks/flights/${flightId}`;

  const options: RequestInit = {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  };

  const result = await fetch(url, options);
  const data = await result.json();

  if (result.status !== 200) {
    return null;
  }

  return data;
}

interface FlightsDetailPageProps {
  params: {
    flightId: string;
  };
}

export default async function FlightsDetailPage({
  params: { flightId },
}: FlightsDetailPageProps) {
  if (!flightId) {
    return notFound();
  }

  const data = await getFlightDetails(flightId);

  if (!data) {
    return notFound();
  }

  return <FlightDetails initialData={data} />;
}
image.png
image.png
Was this page helpful?