Sequential data fetching helps you get data step-by-step, where each step waits for the previous one to finish. This is useful when later data depends on earlier data.
Sequential data fetching in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
async function fetchData() { const firstResponse = await fetch('https://api.example.com/first'); const firstData = await firstResponse.json(); const secondResponse = await fetch(`https://api.example.com/second/${firstData.id}`); const secondData = await secondResponse.json(); return { firstData, secondData }; }
Use await to wait for each fetch to finish before moving on.
Each fetch depends on data from the previous fetch.
Examples
NextJS
const response1 = await fetch('https://api.example.com/user'); const user = await response1.json(); const response2 = await fetch(`https://api.example.com/posts?userId=${user.id}`); const posts = await response2.json();
NextJS
const tokenResponse = await fetch('https://api.example.com/get-token'); const { token } = await tokenResponse.json(); const dataResponse = await fetch('https://api.example.com/data', { headers: { Authorization: `Bearer ${token}` } }); const data = await dataResponse.json();
Sample Program
This React component fetches user info first, then fetches posts for that user. It shows loading text while waiting. When done, it displays the user's name, email, and a list of their post titles.
NextJS
import React, { useState, useEffect } from 'react'; export default function SequentialFetch() { const [user, setUser] = useState(null); const [posts, setPosts] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchUserAndPosts() { try { const userRes = await fetch('https://jsonplaceholder.typicode.com/users/1'); const userData = await userRes.json(); setUser(userData); const postsRes = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userData.id}`); const postsData = await postsRes.json(); setPosts(postsData); } catch (error) { console.error('Error fetching data:', error); } finally { setLoading(false); } } fetchUserAndPosts(); }, []); if (loading) return <p>Loading data...</p>; return ( <main> <h1>User Info</h1> <p><strong>Name:</strong> {user.name}</p> <p><strong>Email:</strong> {user.email}</p> <h2>User Posts</h2> <ul> {posts.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> </main> ); }
Important Notes
Sequential fetching can slow down your app if many steps are needed. Use only when necessary.
For independent data, fetch in parallel to save time.
Always handle errors to avoid app crashes.
Summary
Sequential data fetching gets data step-by-step, waiting for each step.
Use it when later data depends on earlier data.
Use async/await to write clear, readable code for this.
Practice
1. What is the main reason to use sequential data fetching in Next.js?
easy
Solution
Step 1: Understand the dependency in data fetching
Sequential fetching is used when one piece of data needs the result of a previous fetch to continue.Step 2: Compare with other fetching methods
Parallel fetching gets all data at once, but sequential waits for each step because of dependency.Final Answer:
Because later data depends on the results of earlier data -> Option AQuick Check:
Sequential fetching = dependent data steps [OK]
Hint: Use sequential fetching when data depends on previous results [OK]
Common Mistakes:
- Thinking parallel fetching is always better
- Ignoring data dependencies
- Confusing async/await with parallel fetching
2. Which of the following is the correct syntax to fetch data sequentially using async/await in Next.js?
easy
Solution
Step 1: Identify correct async/await usage
Using await before fetch pauses execution until the promise resolves, ensuring sequential order.Step 2: Check syntax correctness
const data1 = await fetch(url1); const data2 = await fetch(url2); uses two separate await statements correctly. const data1 = await fetch(url1), const data2 = await fetch(url2); has a syntax error with comma instead of semicolon.Final Answer:
const data1 = await fetch(url1); const data2 = await fetch(url2); -> Option DQuick Check:
Separate awaits with semicolons = correct syntax [OK]
Hint: Use separate await statements with semicolons for sequential fetch [OK]
Common Mistakes:
- Using commas instead of semicolons between await calls
- Not using await causing parallel fetch
- Using then() without await for sequential logic
3. What will be the output of this Next.js code snippet?
async function fetchData() {
const res1 = await fetch('https://api.example.com/user');
const user = await res1.json();
const res2 = await fetch(`https://api.example.com/posts?userId=${user.id}`);
const posts = await res2.json();
return posts.length;
}medium
Solution
Step 1: Understand sequential fetch calls
The first fetch gets user data, then uses user.id to fetch posts for that user.Step 2: Analyze returned value
The function returns posts.length, which is the count of posts for that user.Final Answer:
The number of posts for the fetched user -> Option CQuick Check:
Sequential fetch returns posts count [OK]
Hint: Check if later fetch depends on earlier data for output [OK]
Common Mistakes:
- Assuming user.id is undefined without checking response
- Confusing posts length with total users
- Thinking async fetch returns zero immediately
4. Identify the error in this sequential data fetching code in Next.js:
async function getData() {
const user = fetch('/api/user');
const posts = await fetch(`/api/posts?userId=${user.id}`);
return posts.json();
}medium
Solution
Step 1: Check fetch usage for user
fetch returns a Promise; without await, user is a Promise, not the data object.Step 2: Understand impact on user.id
Accessing user.id fails because user is not resolved yet, causing runtime error.Final Answer:
Missing await before first fetch causing user to be a Promise -> Option BQuick Check:
Always await fetch to get resolved data [OK]
Hint: Always await fetch before accessing response data [OK]
Common Mistakes:
- Forgetting await before fetch
- Assuming fetch returns data directly
- Not awaiting json() call
5. You want to fetch user info, then fetch their orders, and finally fetch details for each order sequentially in Next.js. Which approach correctly handles this?
hard
Solution
Step 1: Understand sequential dependency
Order details depend on orders, which depend on user info, so fetches must be sequential.Step 2: Use for-of with await for sequential order detail fetch
Using for-of with await inside ensures each order detail fetch waits for the previous to finish.Final Answer:
Use async/await to fetch user, then orders, then loop with await inside for-of to fetch each order detail -> Option AQuick Check:
Sequential fetch with for-of and await = correct approach [OK]
Hint: Use for-of with await for sequential loops in async functions [OK]
Common Mistakes:
- Using map without await causing parallel fetch
- Fetching all data at once ignoring dependencies
- Mixing parallel and sequential fetch incorrectly
