Bird
Raised Fist0
NextJSframework~20 mins

Parallel data fetching in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Parallel Fetching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the rendered output of this Next.js component?

Consider this Next.js component that fetches user and post data in parallel using Promise.all. What will it render?

NextJS
import React from 'react';

async function fetchUser() {
  return { name: 'Alice' };
}

async function fetchPosts() {
  return ['Post1', 'Post2'];
}

export default async function Page() {
  const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
  return (
    <main>
      <h1>User: {user.name}</h1>
      <ul>
        {posts.map((post, i) => <li key={i}>{post}</li>)}
      </ul>
    </main>
  );
}
A<main><h1>User: undefined</h1><ul><li>Post1</li><li>Post2</li></ul></main>
BRuntime error: Cannot read property 'map' of undefined
C<main><h1>User: Alice</h1><ul></ul></main>
D<main><h1>User: Alice</h1><ul><li>Post1</li><li>Post2</li></ul></main>
Attempts:
2 left
💡 Hint

Think about what Promise.all returns and how the data is destructured.

📝 Syntax
intermediate
2:00remaining
Which option correctly fetches data in parallel in a Next.js server component?

Choose the code snippet that correctly fetches data1 and data2 in parallel inside a Next.js server component.

Aconst [data1, data2] = await Promise.all([fetch('/api/data1'), fetch('/api/data2')]);
B
const data1 = await fetch('/api/data1');
const data2 = await fetch('/api/data2');
C
const data1 = fetch('/api/data1');
const data2 = fetch('/api/data2');
await data1;
await data2;
D
const data1 = fetch('/api/data1').then(res =&gt; res.json());
const data2 = fetch('/api/data2').then(res =&gt; res.json());
Attempts:
2 left
💡 Hint

Remember that Promise.all runs promises in parallel and waits for all to finish.

🔧 Debug
advanced
2:00remaining
Why does this parallel fetch code cause a runtime error?

Examine this Next.js server component code snippet. It tries to fetch two APIs in parallel but causes a runtime error. What is the cause?

NextJS
export default async function Page() {
  const data1 = fetch('/api/data1').then(res => res.json());
  const data2 = fetch('/api/data2').then(res => res.json());
  return (
    <main>
      <p>Data1: {data1.value}</p>
      <p>Data2: {data2.value}</p>
    </main>
  );
}
Adata1 and data2 are promises, not resolved data, so accessing .value causes an error.
Bfetch calls are missing await, causing a syntax error.
CThe component must be a client component to use fetch.
DThe API endpoints '/api/data1' and '/api/data2' do not exist, causing a 404 error.
Attempts:
2 left
💡 Hint

Check what fetch(...).then(...) returns and how it is used in JSX.

state_output
advanced
2:00remaining
What is the output of this React component using parallel data fetching with hooks?

Consider this React functional component that fetches two APIs in parallel using useEffect and Promise.all. What will it display after data loads?

NextJS
import React, { useState, useEffect } from 'react';

export default function DataDisplay() {
  const [data, setData] = useState({ user: null, posts: null });

  useEffect(() => {
    Promise.all([
      fetch('/api/user').then(res => res.json()),
      fetch('/api/posts').then(res => res.json())
    ]).then(([userData, postsData]) => {
      setData({ user: userData, posts: postsData });
    });
  }, []);

  if (!data.user || !data.posts) return <p>Loading...</p>;

  return (
    <div>
      <h2>{data.user.name}</h2>
      <ul>
        {data.posts.map(post => <li key={post.id}>{post.title}</li>)}
      </ul>
    </div>
  );
}
A<p>Loading...</p> forever because state never updates.
B<p>Loading...</p> initially, then user name and list of post titles after fetches complete.
CAn error because <code>data.posts</code> is null when mapping.
DUser name displayed but posts list is empty.
Attempts:
2 left
💡 Hint

Think about how useEffect and state updates work asynchronously.

🧠 Conceptual
expert
2:00remaining
Why is parallel data fetching preferred over sequential fetching in Next.js server components?

Choose the best explanation for why fetching multiple data sources in parallel is better than fetching them one after another in Next.js server components.

ASequential fetching allows better error handling and is preferred for reliability.
BSequential fetching is always faster because it avoids network congestion.
CParallel fetching reduces total wait time by running requests simultaneously, improving performance and user experience.
DParallel fetching uses more memory and should be avoided to reduce server load.
Attempts:
2 left
💡 Hint

Think about how waiting for multiple tasks works in real life, like waiting in line versus doing tasks at the same time.

Practice

(1/5)
1. What is the main benefit of using Promise.all for data fetching in Next.js?
easy
A. It fetches multiple data sources at the same time, reducing total wait time.
B. It fetches data sequentially to avoid race conditions.
C. It caches data automatically for offline use.
D. It delays fetching until the user clicks a button.

Solution

  1. Step 1: Understand Promise.all behavior

    Promise.all runs multiple promises in parallel and waits for all to finish.
  2. Step 2: Relate to data fetching speed

    Fetching multiple data sources at once reduces total waiting time compared to sequential fetching.
  3. Final Answer:

    It fetches multiple data sources at the same time, reducing total wait time. -> Option A
  4. Quick Check:

    Parallel fetching = faster load [OK]
Hint: Remember: parallel means 'at the same time' [OK]
Common Mistakes:
  • Thinking Promise.all fetches sequentially
  • Confusing caching with parallel fetching
  • Assuming it delays fetching until user action
2. Which of the following is the correct syntax to fetch two APIs in parallel using Promise.all in Next.js?
easy
A. const [res1, res2] = await Promise.all(fetch(url1), fetch(url2));
B. const [res1, res2] = await Promise.all([fetch(url1), fetch(url2)]);
C. const res1 = await fetch(url1); const res2 = await fetch(url2);
D. const res1 = fetch(url1).then(fetch(url2));

Solution

  1. Step 1: Check Promise.all argument format

    Promise.all expects an array of promises, so the fetch calls must be inside an array.
  2. Step 2: Identify correct syntax

    const [res1, res2] = await Promise.all([fetch(url1), fetch(url2)]); correctly uses an array: Promise.all([fetch(url1), fetch(url2)]). const [res1, res2] = await Promise.all(fetch(url1), fetch(url2)); misses the array brackets.
  3. Final Answer:

    const [res1, res2] = await Promise.all([fetch(url1), fetch(url2)]); -> Option B
  4. Quick Check:

    Array of promises = correct syntax [OK]
Hint: Always wrap promises in an array for Promise.all [OK]
Common Mistakes:
  • Forgetting the array brackets around promises
  • Using sequential awaits instead of Promise.all
  • Chaining fetch calls incorrectly
3. Given this Next.js code snippet, what will be logged to the console?
async function fetchData() {
  const [userRes, postsRes] = await Promise.all([
    fetch('https://api.example.com/user'),
    fetch('https://api.example.com/posts')
  ]);
  console.log(userRes.status, postsRes.status);
}
fetchData();
medium
A. 200 200
B. undefined undefined
C. Promise Promise
D. Error: fetch is not defined

Solution

  1. Step 1: Understand what fetch returns

    Each fetch returns a Response object with a status property indicating HTTP status.
  2. Step 2: Analyze Promise.all result

    Promise.all waits for both fetches and returns an array of Response objects. Logging userRes.status and postsRes.status prints their HTTP status codes.
  3. Final Answer:

    200 200 -> Option A
  4. Quick Check:

    Response.status = 200 if successful [OK]
Hint: fetch returns Response objects with status property [OK]
Common Mistakes:
  • Expecting fetch to return JSON directly
  • Logging promises instead of awaited results
  • Confusing undefined with Response properties
4. What is wrong with this Next.js code that tries to fetch two APIs in parallel?
async function getData() {
  const res1 = fetch('https://api.example.com/data1');
  const res2 = fetch('https://api.example.com/data2');
  const data1 = await res1.json();
  const data2 = await res2.json();
  return { data1, data2 };
}
medium
A. Nothing is wrong; this code fetches data correctly.
B. The fetch calls are not awaited in parallel, causing sequential fetching.
C. The function should use Promise.all to fetch in parallel.
D. You cannot call json() on a promise; you must await the fetch first.

Solution

  1. Step 1: Identify the type of res1 and res2

    Both res1 and res2 are promises from fetch, not Response objects yet.
  2. Step 2: Understand json() usage

    You must await the fetch promise to get the Response object before calling json(). Calling json() directly on a promise causes an error.
  3. Final Answer:

    You cannot call json() on a promise; you must await the fetch first. -> Option D
  4. Quick Check:

    Await fetch before json() [OK]
Hint: Always await fetch before calling json() [OK]
Common Mistakes:
  • Calling json() on a fetch promise without awaiting
  • Assuming fetch returns JSON directly
  • Not using Promise.all for parallelism
5. You want to fetch user info and user posts in parallel in Next.js, but only display posts if user info fetch succeeds. Which approach correctly handles this?
hard
A. Use Promise.all for both fetches and check user info response before rendering posts.
B. Fetch user info first, then fetch posts only if user info fetch succeeds.
C. Use Promise.allSettled to fetch both, then conditionally render posts if user info succeeded.
D. Fetch posts first, then fetch user info regardless of posts fetch result.

Solution

  1. Step 1: Understand requirement for conditional rendering

    Posts should display only if user info fetch succeeds, so we need to know each fetch's success independently.
  2. Step 2: Choose correct parallel fetching method

    Promise.all fails fast if any promise rejects, so it can't handle partial success. Promise.allSettled waits for all promises and reports each result, allowing conditional logic.
  3. Step 3: Apply conditional rendering logic

    After Promise.allSettled, check user info status; if successful, render posts, else skip posts.
  4. Final Answer:

    Use Promise.allSettled to fetch both, then conditionally render posts if user info succeeded. -> Option C
  5. Quick Check:

    Conditional render needs allSettled [OK]
Hint: Use allSettled to handle partial success in parallel fetches [OK]
Common Mistakes:
  • Using Promise.all which fails on first error
  • Fetching posts before confirming user info success
  • Not handling fetch failures gracefully