CodeBlanks Logo Icon CodeBlanks

Challenge: Page with server components

Write a page that fetches products in a server component and passes them to a client component.

Challenge: Page with server components

In this challenge you will write an async server component page. You fetch data with await fetch and return it as HTML.

The page shows a title inside an article tag. Data is fetched on the server; it does not enter the client bundle. The API key stays on the server; it never leaks to the client. The first render is fast.

Practice Write the ArticlePage server component

Write an ArticlePage server component. Take an id prop. Make it an async function. Fetch with await fetch(`/api/articles/${id}`) and parse with res.json(). Return <article><h1>{article.title}</h1></article>. Export it.

Starter code

App.jsx
// Write the ArticlePage server component here

Sample solution

App.jsx
async function ArticlePage({ id }) {
  const res = await fetch(`/api/articles/${id}`);
  const article = await res.json();
  return (
    <article>
      <h1>{article.title}</h1>
    </article>
  );
}
export default ArticlePage;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How does a server component fetch data?

  • With await fetch in an async function Correct answer
  • With useEffect
  • With setInterval
  • With addEventListener

Explanation: Server components use await fetch as async functions.

2 Fill in the blank: async function

Question
async function ArticlePage({ id }) {
  const res = await ____(`/api/articles/${id}`);
  const article = await res.json();
  return <article><h1>{article.title}</h1></article>;
}
Answer
async function ArticlePage({ id }) {
  const res = await fetch(`/api/articles/${id}`);
  const article = await res.json();
  return <article><h1>{article.title}</h1></article>;
}

Explanation: answer: fetch. await fetch makes the request.

All lessons in Expert