0
0
NextJSframework~20 mins

Sequential data fetching in NextJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sequential Fetching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What will this Next.js component render?

Consider this Next.js Server Component that fetches two APIs sequentially. What will it render?

NextJS
import React from 'react';

async function fetchUser() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
  return res.json();
}

async function fetchPosts(userId) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
  return res.json();
}

export default async function UserPosts() {
  const user = await fetchUser();
  const posts = await fetchPosts(user.id);

  return (
    <main>
      <h1>{user.name}</h1>
      <ul>
        {posts.slice(0, 2).map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}
AEmpty <main> because fetchUser returns undefined
B<main> with user name but empty list (no posts)
C<main> with user name and first 2 post titles listed
DError: fetchPosts called before fetchUser resolves
Attempts:
2 left
💡 Hint

Think about the order of await calls and what data is available when rendering.

state_output
intermediate
1:30remaining
What is the value of 'posts' after this code runs?

Given this Next.js Server Component code, what is the value of posts after execution?

NextJS
async function fetchUser() {
  return { id: 5, name: 'Alice' };
}

async function fetchPosts(userId) {
  if (userId !== 5) throw new Error('User not found');
  return ['Post A', 'Post B', 'Post C'];
}

export default async function Page() {
  const user = await fetchUser();
  const posts = await fetchPosts(user.id);
  return null;
}
AError thrown: User not found
B[] (empty array)
Cundefined
D['Post A', 'Post B', 'Post C']
Attempts:
2 left
💡 Hint

Check the user id returned and the condition inside fetchPosts.

📝 Syntax
advanced
1:30remaining
Which option causes a syntax error in this sequential fetch code?

Identify which option contains a syntax error in this Next.js sequential data fetching snippet.

NextJS
async function getData() {
  const user = await fetch('/api/user').then(res => res.json());
  const posts = await fetch(`/api/posts?userId=${user.id}`).then(res => res.json());
  return { user, posts };
}
Aconst user = await fetch('/api/user').then(res => res.json())
Bconst data = await fetch('/api/data').then(res => res.json()
Cconst posts = await fetch(`/api/posts?userId=${user.id}`).then(res => res.json())
Dreturn { user, posts }
Attempts:
2 left
💡 Hint

Look carefully at parentheses and brackets in each line.

🔧 Debug
advanced
2:30remaining
Why does this Next.js component fail to fetch posts correctly?

Examine this component. It fetches user data and then posts. Why does it fail to show posts?

NextJS
import React from 'react';

export default async function UserPosts() {
  const userPromise = fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json());
  const postsPromise = fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userPromise.id}`).then(res => res.json());

  const user = await userPromise;
  const posts = await postsPromise;

  return (
    <main>
      <h1>{user.name}</h1>
      <ul>
        {posts.slice(0, 2).map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}
ApostsPromise uses userPromise.id before userPromise resolves, so userPromise.id is undefined
Bfetch URLs are incorrect and cause 404 errors
Cawait is missing before fetch calls, so promises never resolve
DpostsPromise is awaited before userPromise, causing race condition
Attempts:
2 left
💡 Hint

Check when userPromise.id is accessed relative to promise resolution.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of sequential data fetching in Next.js Server Components?

Choose the best explanation for why sequential data fetching is used in Next.js Server Components.

AIt allows fetching dependent data step-by-step, ensuring later fetches use data from earlier ones
BIt speeds up data fetching by running all requests in parallel
CIt reduces server load by caching all fetches automatically
DIt enables client-side rendering to happen faster
Attempts:
2 left
💡 Hint

Think about when you need data from one fetch to use in the next fetch.