FRONTENDO
Emberhold Forge
0
0
Next.js · Data Fetching
New technique

Fetch where you render

No more fetching ore in useEffect and waiting with a spinner. A Server Component just walks to the mine and gets it.

In plain React you render first, then fetch in useEffect, then render again with the data. A Server Component turns that around: it runs on the server, so it can simply await its data and render once, with everything in place.

// app/halls/page.tsx
const Halls = async () => {
  const res = await fetch("https://api.emberhold.dev/halls");
  if (!res.ok) throw new Error("Could not load halls");
  const halls = await res.json();
  return <ul>{halls.map((h) => <li key={h.id}>{h.name}</li>)}</ul>;
};

export default Halls;
  • Server Components can be async and await data directly: from fetch, a database or the file system.
  • Check res.ok: a 404 or 500 doesn't throw on its own. A thrown error shows the nearest error.tsx.
  • Keys and database passwords stay on the server and never reach the browser.
  • History: the old Pages Router used getServerSideProps (per request) and getStaticProps (at build). The App Router doesn't need them.