Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentintermediate

Server မှ Data Fetching

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Async page မှာ fetch သုံးရန်
  • HTTP error ကို စစ်ဆေးရန်
  • Data access ကိုလိုအပ်သည့် component နားမှာထားရန်

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 အချိန်လည်း အဆင်ပြေပါတယ်။

အတူတူ စမ်းရေးကြည့်မယ်

tsx
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 ပြောင်းရလွယ်ပါတယ်။

You should see
Server ကယူလာသော note title များကို HTML list အဖြစ်ပြမည်။

၅ မိနစ် စမ်းကြည့်

Public API တစ်ခုက data ယူပြီး response.ok စစ်ကာ အနည်းဆုံး field နှစ်ခုကို card အဖြစ်ပြပါ။

Next.js — Fetching DataNext.js

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • response.ok မစစ်ဘဲ response.json() တန်းခေါ်ခြင်း
  • Server Component မှ ကိုယ့် app Route Handler ကို localhost URL ဖြင့်ပြန်ခေါ်ခြင်း

လေ့ကျင့်ခန်း

Public API တစ်ခုက data ယူပြီး response.ok စစ်ကာ အနည်းဆုံး field နှစ်ခုကို card အဖြစ်ပြပါ။

You'll know it worked when: Server ကယူလာသော note title များကို HTML list အဖြစ်ပြမည်။

Server မှ Data Fetching | Thuta Learning