Complete the code to fetch data sequentially inside a React Server Component.
export default async function Page() {
const data1 = await fetch('/api/data1').then(res => res.json());
const data2 = await [1]('/api/data2').then(res => res.json());
return <div>{data1.title} - {data2.title}</div>;
}The fetch function is used to get data sequentially in Next.js Server Components. Here, await fetch ensures the second fetch waits for the first.
Complete the code to fetch two APIs one after another and combine their results.
export default async function Page() {
const res1 = await fetch('/api/user');
const user = await res1.json();
const res2 = await fetch(`/api/posts?userId=${user.id}`);
const posts = await [1].json();
return <main>{user.name} has {posts.length} posts.</main>;
}After fetching res2, you call res2.json() to parse the posts data.
Fix the error in the code to fetch data sequentially and render it.
export default async function Page() {
const data1 = await fetch('/api/data1').then(res => res.json());
const data2 = [1] fetch('/api/data2').then(res => res.json());
return <div>{data1.name} and {data2.name}</div>;
}The second fetch must be awaited to get the resolved data before rendering.
Fill both blanks to create a sequential fetch and parse JSON for two APIs.
export default async function Page() {
const response1 = await fetch('/api/info');
const info = await response1[1]();
const response2 = await fetch('/api/details');
const details = await response2[2]();
return <section>{info.title} - {details.description}</section>;
}Use .json() to parse the fetch response as JSON data for both responses.
Fill all three blanks to fetch user, then posts, then comments sequentially and parse JSON.
export default async function Page() {
const userRes = await fetch('/api/user');
const user = await userRes[1]();
const postsRes = await fetch(`/api/posts?userId=${user.id}`);
const posts = await postsRes[2]();
const commentsRes = await fetch(`/api/comments?postId=${posts[0].id}`);
const comments = await commentsRes[3]();
return <article>{user.name} has {posts.length} posts and {comments.length} comments on the first post.</article>;
}All fetch responses must be parsed as JSON using .json() to access the data.