Complete the code to fetch data from an API in a Next.js server component.
export default async function Page() {
const res = await fetch('[1]');
const data = await res.json();
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}The fetch URL must be a full API endpoint string. Here, 'https://api.example.com/data' is a valid external API URL.
Complete the code to ensure the fetch call does not cache the response.
export default async function Page() {
const res = await fetch('https://api.example.com/data', { cache: '[1]' });
const data = await res.json();
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}Using 'no-store' disables caching and always fetches fresh data in Next.js server components.
Fix the error in the fetch call to correctly handle server component data fetching.
export default async function Page() {
const res = fetch('https://api.example.com/data');
const data = await [1];
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}You must await the promise returned by res.json() to get the parsed data.
Fill both blanks to fetch data and handle errors in a Next.js server component.
export default async function Page() {
try {
const res = await fetch('https://api.example.com/data', { [1] });
if (!res.ok) throw new Error('Failed to fetch');
const data = await res.[2]();
return <pre>{JSON.stringify(data, null, 2)}</pre>;
} catch (error) {
return <p>Error: {error.message}</p>;
}
}Use 'cache: no-store' to avoid caching and call res.json() to parse the response.
Fill all three blanks to create a server component that fetches data, disables caching, and displays a loading message.
import React from 'react'; export default async function Page() { const res = await fetch('https://api.example.com/data', { [1] }); if (!res.ok) throw new Error('Failed to fetch'); const data = await res.[2](); return ( <main> <h1>Data</h1> <pre>{JSON.stringify(data, null, 2)}</pre> <p aria-live="polite">[3]</p> </main> ); }
Set cache to 'no-store' to disable caching, call res.json() to parse JSON, and show a polite loading message for accessibility.