0
0
NextJSframework~30 mins

Sequential data fetching in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Sequential Data Fetching in Next.js
📖 Scenario: You are building a simple Next.js app that fetches user data and then fetches posts for that user. This simulates a real-world case where you need to get data step-by-step from different sources.
🎯 Goal: Create a Next.js component that fetches user data first, then uses that data to fetch posts for that user sequentially. Display the user's name and their posts.
📋 What You'll Learn
Create a React functional component called UserPosts
Fetch user data from https://jsonplaceholder.typicode.com/users/1
Store the user data in a state variable called user
Fetch posts for the user from https://jsonplaceholder.typicode.com/posts?userId=1
Store the posts in a state variable called posts
Display the user's name and a list of their post titles
Use useEffect to perform the sequential data fetching
Handle loading states with a loading state variable
💡 Why This Matters
🌍 Real World
Sequential data fetching is common when you need to get data step-by-step, such as fetching user info first, then fetching related data like posts or comments.
💼 Career
Understanding how to fetch data sequentially and manage loading states is essential for building responsive and user-friendly web applications in Next.js and React.
Progress0 / 4 steps
1
Setup the UserPosts component and user state
Create a React functional component called UserPosts. Inside it, create a state variable called user initialized to null. Also create a loading state variable initialized to true.
NextJS
Need a hint?

Use useState to create user and loading state variables inside the UserPosts component.

2
Add posts state variable
Inside the UserPosts component, add a state variable called posts initialized to an empty array [].
NextJS
Need a hint?

Add a posts state variable using useState initialized to an empty array.

3
Fetch user data and then posts sequentially
Inside useEffect, fetch user data from https://jsonplaceholder.typicode.com/users/1. After receiving the user data, set it to user. Then fetch posts for that user from https://jsonplaceholder.typicode.com/posts?userId=1 and set them to posts. Finally, set loading to false. Use async/await inside useEffect.
NextJS
Need a hint?

Use an async function inside useEffect to fetch user data first, then posts, updating state variables accordingly.

4
Render user name and post titles with loading state
In the UserPosts component, render a <div>. If loading is true, show Loading.... Otherwise, show the user's name inside an <h1> and a list of post titles inside <li> elements within a <ul>.
NextJS
Need a hint?

Use conditional rendering to show loading text or the user name and posts list.