React client app တွေမှာ useEffect ထဲ fetch ရေးပြီး loading state သီးခြားထိန်းရတာကို တွေ့ဖူးပါလိမ့်မယ်။ Server Component မှာတော့ component ကို async လုပ်ပြီး data ကို await လုပ်ကာ အဆင်သင့် HTML ကိုပို့နိုင်ပါတယ်။
နားလည်ထားရမယ့် အချက်
Server Component က browser မပို့ခင် server မှာ run လို့ API key နဲ့ database connection ကို လုံခြုံစွာသုံးနိုင်ပါတယ်။ fetch က 404 သို့မဟုတ် 500 အတွက် အလိုအလျောက် throw မလုပ်တာကြောင့် response.ok ကို ကိုယ်တိုင်စစ်ရပါတယ်။ ကိုယ့် app ရဲ့ Server Component က ကိုယ့် Route Handler ကို HTTP ပြန်ခေါ်မယ့်အစား data source ကို တိုက်ရိုက်ခေါ်တာ ပိုမြန်ပြီး build အချိန်လည်း အဆင်ပြေပါတယ်။
အတူတူ စမ်းရေးကြည့်မယ်
type Note = { id: string; title: string };
async function getNotes(): Promise<Note[]> {
const response = await fetch("https://api.example.com/notes");
if (!response.ok) throw new Error("မှတ်စုများ ယူမရပါ");
return response.json();
}
export default async function NotesPage() {
const notes = await getNotes();
return (
<ul>
{notes.map((note) => <li key={note.id}>{note.title}</li>)}
</ul>
);
}Code က ဘယ်လိုအလုပ်လုပ်သလဲ
getNotes က response type ကိုသတ်မှတ်ပြီး error စစ်ပါတယ်။ Page က data ရပြီးမှ list ပြပါတယ်။ API URL ကိုတစ်နေရာတည်း function ထဲထားလို့ နောက်ပိုင်း source ပြောင်းရလွယ်ပါတယ်။
Server ကယူလာသော note title များကို HTML list အဖြစ်ပြမည်။၅ မိနစ် စမ်းကြည့်
Public API တစ်ခုက data ယူပြီး response.ok စစ်ကာ အနည်းဆုံး field နှစ်ခုကို card အဖြစ်ပြပါ။
Next.js — Fetching Data — Next.js