Next.js Server-Side Data Fetching — fetch() in Server Components
API request fail అయితే, app crash కాకుండా handle చేయడం important:
async function getCourses() {
const response = await fetch("https://api.example.com/courses");
if (!response.ok) {
throw new Error("Failed to fetch courses");
}
return response.json();
}
throw new Error(...) చేస్తే, Next.js automatic ga దగ్గరలో unна error.tsx (Chapter 19) fallback UI ni trigger చేస్తుంది.
రెండు independent API calls, ఒకదాని తర్వాత ఒకటి (sequential) కాకుండా, ఒకేసారి (parallel) run చేస్తే page load వేగంగా అవుతుంది:
async function getUser() {
return fetch("https://api.example.com/user").then((r) => r.json());
}
async function getStats() {
return fetch("https://api.example.com/stats").then((r) => r.json());
}
export default async function Dashboard() {
const [user, stats] = await Promise.all([getUser(), getStats()]);
return (
<div>
<h1>Welcome, {user.name}</h1>
<p>Total Views: {stats.views}</p>
</div>
);
}
Promise.all([...]), rెండు fetch calls ni ఒకేసారి start చేసి, రెండూ complete అయ్యే వరకు wait చేస్తుంది — mొత్తం time = slowest request time matrame (sum కాదు).
Konni సందర్భాలలో, రెండో request, మొదటి request result meedhа depend అవుతుంది — అప్పుడు sequential fetching తప్పనిసరి:
export default async function Profile() {
const user = await fetch("https://api.example.com/user").then((r) => r.json());
const orders = await fetch(`https://api.example.com/orders?userId=${user.id}`).then((r) => r.json());
return (
<div>
<h1>{user.name}'s Orders</h1>
<p>Total Orders: {orders.length}</p>
</div>
);
}
Next.js automatic ga, same URL కి same render pass లో multiple components fetch request చేస్తే, actual network call ఒక్కసారి matrame చేసి, result ni అన్ని components కి share చేస్తుంది — దీన్ని manual ga cache చేయాల్సిన అవసరం లేదు.
Independent (ఒకదానితో ఒకటి సంబంధం లేని) API calls ni వరుసగా await చేస్తే (await A; await B;), page load unnecessarily slow అవుతుంది. అవి independent అయితే, Promise.all([A, B]) వాడి parallel గా run చేయాలి.
Fetch both 'products' and 'categories' from two different endpoints in parallel using Promise.all, then render both counts.
async function getProducts() {
return fetch("https://api.example.com/products").then((r) => r.json());
}
async function getCategories() {
return fetch("https://api.example.com/categories").then((r) => r.json());
}
export default async function ShopPage() {
const [products, categories] = await Promise.all([getProducts(), getCategories()]);
return <p>{products.length} products in {categories.length} categories</p>;
}
Q response.ok check ఎప్పుడూ compulsory ah?
Strictly compulsory kాదు, kani production apps లో strongly recommended — లేకపోతే failed request (404, 500) valla page silently broken data తో render అవుతుంది.
Q Promise.all లో ఒక request fail అయితే ఏమవుతుంది?
Promise.all, ఏదైనా ఒక్క promise reject అయితే, మొత్తం fail అవుతుంది. అన్ని requests independent గా handle చేయాలంటే Promise.allSettled() వాడాలి.
Q Request deduplication client-side fetch కి కూడా apply అవుతుందా?
Ledు, ఇది Server Component fetch() calls కి matrame (ఒకే render pass లో) apply అవుతుంది. Client-side fetching (Chapter 17) కి వేరే caching strategy (SWR/React Query) అవసరం.