0
0
NextJSframework~5 mins

Sequential data fetching in NextJS

Choose your learning style9 modes available
Introduction

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.

When you need to fetch user info first, then fetch that user's posts.
When you get a list of IDs first, then fetch details for each ID one by one.
When an API requires a token from one request before making the next request.
When you want to show loading progress step-by-step in your app.
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
Fetch user data first, then fetch posts for that user.
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();
Fetch a token first, then use it to fetch protected data.
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>
  );
}
OutputSuccess
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.