I'm always excited to take on new projects and collaborate with innovative minds.

Address

Kayseri, Turkey

Social

Sequential Data Fetching in Next.js Server Components

Hello, fellow code lovers! 🙌 Today I'm going to tell you how I handled sequential data fetching in Next.js Server Components. I broke a bit of a sweat wrestling with dependent API requests, but in the end everything ran like clockwork! 😎 We'll use the JSONPlaceholder API to build a blog-like interface and fetch the data one piece at a time. If you're ready, let's dive into the world of code! 🚀

Sequential Data Fetching in Next.js Server Components

My Sequential Data Fetching Adventure with Next.js: Dancing with Data! 💃🕺

Hello, fellow code lovers! 🙌 Today I'm going to tell you how I handled sequential data fetching in Next.js Server Components. I broke a bit of a sweat wrestling with dependent API requests, but in the end everything ran like clockwork! 😎 We'll use the JSONPlaceholder API to build a blog-like interface and fetch the data one piece at a time. If you're ready, let's dive into the world of code! 🚀

Why Sequential Data Fetching? 🤔

There are two ways to fetch data:

  • Parallel: Everything loads at the same time, a total chaos party! 🎉
  • Sequential: One piece of data depends on another, just like a domino effect. 🁡

In this post we're focusing on sequential fetching, because sometimes the result of one API is required to call another. For example, fetching the blog posts first and then grabbing each post's author. Is it slow? Yep, a little. But sometimes this is just how the dance has to go! 😜

What Are We Building? 📝

We'll be playing with the JSONPlaceholder API:

  • /posts: Returns blog posts (each one has a userId).
  • /users/:id: Fetches the details of the post's author.

Our goal: get the posts first, then look at each post's userId and fetch the author's name. Let's code! 💻

Code Time: Sequential Data Fetching 🎬

First up, let's tackle sequential data fetching in a Next.js Server Component. Here's the code I wrote, have a taste:

// app/posts/page.jsx
async function fetchPosts() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  return res.json();
}

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

export default async function PostsPage() {
  const posts = await fetchPosts();

  return (
    <div>
      <h1>Blog Gönderileri 🚀</h1>
      <ul>
        {posts.map(async (post) => {
          const user = await fetchUser(post.userId);
          return (
            <li key={post.id}>
              <h2>{post.title}</h2>
              <p>Yazar: {user.name} ✍️</p>
              <p>{post.body}</p>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

What Does This Code Do? 🧐

  • fetchPosts: Collects all the blog posts.
  • fetchUser: Fetches the author's details based on the given userId.
  • For each post, I take the userId and fetch the author info one after another. Thanks to async/await, everything stays neat and tidy! 😇

But let's be honest, this approach is a bit slow. We're firing off a request for each user one by one, as if we're waiting our turn in a queue. 🐢

Let's Put On a Show with Suspense! 🎭

Enter Next.js's Suspense feature! It's a classy way of telling the user "hang on a sec, I'm grabbing a coffee" while the data loads. ☕ We load each post separately and show a "Loading…" message while it's loading. Here's the code:

// app/posts/page.jsx
import { Suspense } from 'react';

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

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

async function PostItem({ post }) {
  const user = await fetchUser(post.userId);
  return (
    <li>
      <h2>{post.title}</h2>
      <p>Yazar: {user.name} ✍️</p>
      <p>{post.body}</p>
    </li>
  );
}

export default async function PostsPage() {
  const posts = await fetchPosts();

  return (
    <div>
      <h1>Blog Gönderileri 🚀</h1>
      <ul>
        {posts.map((post) => (
          <Suspense key={post.id} fallback={<p>Yükleniyor... ⏳</p>}>
            <PostItem post={post} />
          </Suspense>
        ))}
      </ul>
    </div>
  );
}

Why Is Suspense Awesome? 😍

  • Chunked Loading: Each post loads at its own pace; if one gets stuck, the others keep going.
  • Keep the User Happy: We keep the user entertained with a "Loading…" message so they don't get bored! 😜
  • Modularity: Our code is now more organized, just like a LEGO set! 🧱

Ways to Boost Performance 🚀

Sequential data fetching is a bit sluggish, I'll admit. But we can speed it up with a few tricks:

  • Use a Cache: Let's not fetch the same userId over and over. Let's set up a cache with a Map:
const userCache = new Map();

async function fetchUser(userId) {
  if (userCache.has(userId)) {
    return userCache.get(userId);
  }
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
  const user = await res.json();
  userCache.set(userId, user);
  return user;
}
  • Think Parallel: If some of the data is independent, try fetching it in parallel.
  • Next.js's Fetch Cache: Use Next.js's own caching wizardry and cut down on requests! 🪄

Final Words 🎤

We cracked sequential data fetching with Next.js Server Components and Suspense! 😎 Playing around with JSONPlaceholder, we learned a lot and had fun along the way. If you're working with dependent data, tools like Suspense and caching can make your app fly. 🚀

How do you handle sequential data fetching? Tell me in the comments, maybe you've got an even cooler approach than mine! 😜 Keep coding, see you around! 👋

Author Ahmet Yüceler

I build web and mobile products with 6+ years of experience. I share what I learn here.

Get in touch →

Leave a comment

Your email address will not be published. Required fields are marked *