Thuta Learning
Next.js
IntermediateWeb Developmentအလယ်အလတ်

Server မှ Data Fetching

Next.jsသင်ခန်းစာ 1335 မိနစ်

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

  • Server Component ကို async လုပ်ပြီး data ကို render မလုပ်ခင် await လုပ်နိုင်ဖို့
  • fetch က 404/500 မှာ throw မလုပ်တာကို သိပြီး response.ok ကို စစ်နိုင်ဖို့
  • Promise.all နဲ့ အမှီအခိုကင်းတဲ့ request တွေကို waterfall မဖြစ်အောင် ပို့နိုင်ဖို့
  • ကိုယ့် Route Handler ကို HTTP နဲ့ ပြန်မခေါ်ဘဲ data function ကို တိုက်ရိုက် ခေါ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Server ပေါ်က data fetching ကို ရိုးရိုးလေး ပြောရရင်

React client app မှာ data ယူရတာက အိမ်ရောက်မှ ဈေးသွားရသလိုပါ: page က အလွတ်နဲ့ ပေါ်လာပြီး useEffect က fetch လုပ်၊ loading state ပြ၊ data ရောက်မှ ဖြည့်ရပါတယ်။ Server Component မှာတော့ ဈေးကို အရင်ဝယ်ပြီးမှ ဧည့်သည်ကို ခေါ်သလိုပါပဲ: component ကို async လုပ်၊ data ကို await လုပ်ပြီး အဆင်သင့် HTML ကို ပို့ပါတယ်။

Server ပေါ်မှာ run တာမို့ API key နဲ့ database password တွေကို browser မမြင်ရပါဘူး၊ data source နဲ့လည်း နီးလို့ ပိုမြန်လေ့ရှိပါတယ်။

Problem → Why → Solution

ပြဿနာ: useEffect fetch နဲ့ မစစ်ထားတဲ့ response

React lesson တွေကနေ ကူးလာတဲ့ အောက်က component က Next.js ထဲမှာလည်း အလုပ်လုပ်ပါတယ်၊ ဒါပေမဲ့ ပြဿနာ နှစ်ခု ရှိပါတယ်။ User က အရင်ဆုံး 'Loading…' ကိုပဲ မြင်ပြီး search engine ကလည်း note title တွေကို HTML ထဲမှာ မတွေ့ပါဘူး။ ဒုတိယ — API က 500 ပြန်တဲ့နေ့မှာ error JSON ကို note array လို့ ထင်ပြီး notes.map is not a function နဲ့ crash ဖြစ်ပါတယ်။

app/notes/page.tsx
"use client";
import { useEffect, useState } from "react";

export default function NotesPage() {
  const [notes, setNotes] = useState<{ id: string; title: string }[] | null>(null);
  useEffect(() => {
    fetch("https://api.example.com/notes")
      .then((response) => response.json()) // a 500 body is parsed as "notes" too
      .then(setNotes);
  }, []);
  if (!notes) return <p>Loading…</p>; // this is all crawlers and slow phones see
  return <ul>{notes.map((note) => <li key={note.id}>{note.title}</li>)}</ul>;
}

ဒါက ဘာကြောင့် အရေးကြီးတာလဲ

fetch() က network ကိုယ်တိုင် fail မှသာ reject လုပ်ပါတယ်၊ 404 နဲ့ 500 ကတော့ ok: false ပါတဲ့ ရိုးရိုး response ပါ။ Status မစစ်ရင် error body ကို data လို ပြပါတယ်။ Server Component မှာ data ကို render မလုပ်ခင် ယူပြီး မမှန်ရင် throw လုပ်လိုက်ရင် lesson 10 ရဲ့ error.tsx က ဖမ်းပေးပြီး HTML ထဲမှာလည်း data အပြည့်ပါပါတယ်။

Core concept: render မလုပ်ခင် await လုပ်ခြင်း

Server Component က async function ဖြစ်နိုင်လို့ render လုပ်တဲ့ function body ထဲမှာပဲ await fetch(...) ဒါမှမဟုတ် await db.query(...) ကို ရေးလို့ ရပါတယ်။ ORM ဒါမှမဟုတ် database client ကို တိုက်ရိုက် သုံးလည်း credential တွေ client bundle ထဲ မဝင်ပါဘူး။ ဒါပေမဲ့ lesson 20 မှာ လေ့လာမယ့်အတိုင်း user က ဒီ data ကို ကြည့်ခွင့်ရှိမရှိကိုတော့ ကိုယ်တိုင် စစ်ရပါသေးတယ်။

fetch ရဲ့ ရလဒ်ကို သုံးတဲ့ ပုံစံ သုံးဆင့် ရှိပါတယ်: request ပို့၊ response.ok ကို စစ်ပြီး မမှန်ရင် status ပါတဲ့ error ကို throw၊ ပြီးမှ response.json() ကို ခေါ်ပါ။ response.json() ရဲ့ type က any ဖြစ်လို့ Promise<Note[]> လို return type ပေးတာက compiler ကို ကတိပေးတာသာ ဖြစ်ပြီး runtime မှာ စစ်တာ မဟုတ်ပါဘူး၊ ယုံကြည်ရမှု နည်းတဲ့ API ဆိုရင် zod လို library နဲ့ စစ်ပါ။

Caching default ကို version အလိုက် သတိထားပါ။ Next.js 14 မှာ fetch ကို default အားဖြင့် cache လုပ်ခဲ့ပေမဲ့ Next.js 15 ကစပြီး fetch ရလဒ်ကို default အားဖြင့် cache မလုပ်တော့ပါဘူး၊ request တိုင်းမှာ data အသစ် ယူပါတယ်။ Cache လုပ်ချင်ရင် lesson 15 ရဲ့ "use cache" ကို သုံးပါ၊ အသေးစိတ်ကို Next.js docs ရဲ့ Fetching Data နဲ့ Caching စာမျက်နှာမှာ ကြည့်ပါ။ Cache နဲ့ မတူတာက memoization ပါ: render တစ်ကြိမ်အတွင်း URL နဲ့ option တူတဲ့ fetch တွေကို တစ်ကြိမ်ပဲ ပို့လို့ component အများကြီးက data တူကို props မဖြတ်ဘဲ ကိုယ်တိုင် fetch လုပ်လို့ ရပါတယ်။

ကိုယ့် app ထဲက data ဆိုရင် Server Component ကနေ ကိုယ့် Route Handler (/api/notes) ကို HTTP နဲ့ ပြန်မခေါ်ပါနဲ့။ နှစ်ခုလုံး server ပေါ်မှာ run တာမို့ network round trip အပို ဖြစ်ပြီး build time မှာ server မရှိသေးလို့ fail ဖြစ်နိုင်ပါတယ်။ Route Handler ထဲမှာ သုံးတဲ့ getNotes() function ကိုပဲ တိုက်ရိုက် import လုပ်ပြီး ခေါ်ပါ။ Request တစ်ခုအတွင်း component အများကြီးက database function တစ်ခုကို ခေါ်ရင် React ရဲ့ cache() နဲ့ ဝိုင်းထားပါ၊ ဒါမှ query က တစ်ကြိမ်ပဲ run ပါမယ်။

Server data ရဲ့ ခရီး
  1. Request ဝင် → async component run
  2. fetch/db ကို await
  3. ok မဟုတ်ရင် throw → error.tsx
  4. Data ပါတဲ့ HTML ကို ပို့

Browser က loading state မစောင့်ရဘဲ data ပါပြီးသား HTML ကို တန်းရပါတယ်။ စောင့်ချိန် ရှည်ရင် lesson 14 ရဲ့ streaming ကို သုံးပါ။

အထွေထွေ ပုံစံ

tsx
async function loadThing(): Promise<Thing> {
  const response = await fetch(url, options);
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

export default async function Page() {
  const thing = await loadThing();
  return <View thing={thing} />;
}

Data ယူတာကို typed function တစ်ခုထဲ ထားပြီး status ကို စစ်ပါ။ Page က အဲဒီ function ကို await လုပ်ပြီး ရလဒ်ကို render လုပ်ရုံပါပဲ။

Worked example: note list ကို server ပေါ်မှာ ယူခြင်း

အောက်က page က problem section ထဲက useEffect version ကို အစားထိုးပါတယ်။ "use client"၊ useState နဲ့ loading branch တွေ မလိုတော့ပါဘူး၊ ပြီးတော့ API URL က getNotes ဆိုတဲ့ နေရာတစ်ခုတည်းမှာပဲ ရှိပါတယ်။

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 ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A typed loaderasync function getNotes(): Promise<Note[]> {

    Data ယူတဲ့ logic ကို function တစ်ခုထဲ စုထားလို့ နောက်ပိုင်း database ပြောင်းရင် ဒီနေရာတစ်ခုပဲ ပြင်ရပါတယ်။

  2. Check the statusif (!response.ok) throw new Error("Could not load notes");

    404/500 မှာ fetch က reject မလုပ်လို့ ကိုယ်တိုင် throw လုပ်ပါတယ်။ အနီးဆုံး error.tsx က ဒီ error ကို ဖမ်းပါတယ်။

  3. An async pageexport default async function NotesPage() {

    Page component ကိုယ်တိုင် async ဖြစ်လို့ render မလုပ်ခင် data ကို စောင့်နိုင်ပါတယ်။

  4. Await, then renderconst notes = await getNotes();

    ဒီ line ပြီးမှ JSX ကို return လုပ်လို့ browser ရောက်လာတဲ့ HTML ထဲမှာ note title တွေ ပါပြီးသား ဖြစ်ပါတယ်။

You should see
Server ကယူလာသော note title များကို HTML list အဖြစ်ပြမည်။
Response တစ်ခုကို ကိုင်တွယ်ပုံ
  1. fetch(url) ကို await
  2. response.ok ကို စစ်
  3. response.json() ကို return

ok: true (200-299)

Data is rendered into the HTML

ok: false (404, 500...)

throw: the nearest error.tsx shows

Waterfall ကို ရှောင်ခြင်း: Promise.all

Component တစ်ခုထဲမှာ await နှစ်ခုကို တစ်ခုပြီးတစ်ခု ရေးရင် ဒုတိယ request က ပထမ ပြီးမှ စပါတယ်။ ဒုတိယ request က ပထမရဲ့ ရလဒ်ကို မလိုရင် request နှစ်ခုလုံးကို အရင် စလိုက်ပြီး Promise.all နဲ့ အတူ စောင့်ပါ။ Request တစ်ခု fail ရင် Promise.all တစ်ခုလုံး fail ဖြစ်လို့ တစ်စိတ်တစ်ပိုင်း ပြလို့ရချင်ရင် Promise.allSettled ကို သုံးပါ။ Album တွေ မယူခင် artist id လိုသလို ဒုတိယ request က ပထမရဲ့ ရလဒ်ကို တကယ်လိုရင်တော့ အစီအစဉ်ကို ရှောင်လို့ မရပါဘူး၊ အဲဒီ ဒုတိယ အပိုင်းကို page တစ်ခုလုံး မပိတ်ဘဲ stream လုပ်နည်းကို lesson 14 မှာ ပြပါမယ်။

text
Sequential vs parallel (1 s + 2 s requests)
-------------------------------------------
sequential:  [ notes 1s ][ stats 2s ]          -> about 3 s
parallel:    [ notes 1s ]
             [ stats 2s        ]                -> about 2 s
app/dashboard/page.tsx
export default async function DashboardPage() {
  // both requests start now; neither waits for the other
  const [notes, stats] = await Promise.all([getNotes(), getStats()]);
  return <Dashboard notes={notes} stats={stats} />;
}

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Production project တွေမှာ fetch ကို page ထဲမှာ ကြဲမထားဘဲ lib/ ဒါမှမဟုတ် data/ folder ထဲက data access function တွေထဲ စုထားလေ့ရှိပါတယ်။ Page တွေက ဒီ function တွေကိုပဲ ခေါ်ပြီး URL၊ header၊ error handling တို့ကို တစ်နေရာတည်းမှာ ထိန်းပါတယ် (lesson 19)။

  • Headless CMS ကနေ blog post ယူတဲ့ function က API token ကို process.env ကနေ ဖတ်ပြီး Server Component ထဲမှာပဲ သုံးလို့ token က browser ဆီ မရောက်ပါဘူး။
  • Dashboard page က user၊ order နဲ့ revenue data ကို Promise.all နဲ့ တစ်ပြိုင်နက် ယူပြီး အနှေးဆုံး request ကိုသာ စောင့်ပါတယ်။
  • ORM query တွေကို React ရဲ့ cache() နဲ့ ဝိုင်းထားလို့ layout နဲ့ page နှစ်ခုလုံးက getCurrentUser() ကို ခေါ်လည်း request တစ်ခုအတွင်း database ကို တစ်ကြိမ်ပဲ မေးပါတယ်။
  • Development အတွင်း next.config ထဲက logging option က server fetch တိုင်းကို URL နဲ့ print ထုတ်ပေးနိုင်လို့ နှေးတဲ့ ဒါမှမဟုတ် ထပ်နေတဲ့ request တွေကို ရှာရလွယ်ပါတယ်။

အမှားများ

Data fetching နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

response.ok မစစ်ဘဲ response.json() ကို တန်းခေါ်ခြင်း

Server က 500 နဲ့ { "error": "..." } ပြန်ရင် ဒီ object က Note[] အဖြစ် page ထဲ ရောက်ပြီး map လုပ်တဲ့နေရာမှာ နားလည်ရခက်တဲ့ error နဲ့ fail ဖြစ်ပါတယ်။ Status ကို အရင်စစ်ပြီး URL နဲ့ status ပါတဲ့ error message ကို throw လုပ်ပါ။

ကိုယ့် Route Handler ကို localhost URL နဲ့ ပြန်ခေါ်ခြင်း

await fetch("http://localhost:3000/api/notes") က development မှာ အလုပ်လုပ်ပေမဲ့ deploy လုပ်ပြီးရင် host မှားနိုင်ပြီး next build မှာ server မရှိလို့ fail ဖြစ်နိုင်ပါတယ်။ Route Handler နဲ့ page နှစ်ခုလုံးက data function တစ်ခုတည်းကို import လုပ်ပြီး သုံးပါ။

အမှီအခိုကင်းတဲ့ request တွေကို တစ်ခုပြီးတစ်ခု await ခြင်း

const a = await getA(); const b = await getB(); မှာ getB က a ကို မလိုရင် အချိန်ကို အလကား ဖြုန်းနေတာပါ။ နှစ်ခုလုံးကို Promise.all နဲ့ ပေါင်းပါ။

Best Practices

Best practices

  • Data ကို သုံးမယ့် component နားမှာပဲ ယူပါ၊ memoization ကြောင့် request တူကို နေရာနှစ်ခုက ခေါ်လည်း တစ်ကြိမ်ပဲ ပို့ပါတယ်။
  • Error message ထဲမှာ URL path နဲ့ status ထည့်ပါ၊ server log ဖတ်တဲ့အခါ ဘယ် request fail လဲ ချက်ချင်း သိရပါတယ်။
  • API key တွေကို NEXT_PUBLIC_ prefix မပါတဲ့ environment variable မှာ ထားပြီး Server Component ထဲကနေပဲ ဖတ်ပါ။
  • ပြင်ပ API က ပြန်ပေးတဲ့ JSON ကို ယုံကြည်ရမှု နည်းရင် TypeScript type တစ်ခုတည်းကို အားမကိုးဘဲ runtime မှာ စစ်ပါ။

Mini challenge

Mini challenge: dashboard အတွက် data layer

Dashboard page မှာ သုံးမယ့် data function နှစ်ခု ရေးပါ။ getJson<T> က URL တစ်ခုကို fetch လုပ်ပြီး status မမှန်ရင် path နဲ့ status ပါတဲ့ error ကို throw လုပ်ရပါမယ်။ loadDashboard က /notes နဲ့ /stats ကို parallel ယူပြီး title စာရင်းနဲ့ total ကို ပြန်ပေးရပါမယ်။ Starter ထဲက fake API နဲ့ Node မှာ တိုက်ရိုက် run လို့ ရပါတယ်။

  • getJson က response.ok မဟုတ်ရင် 'GET /path failed with 500' ပုံစံ error ကို throw ရမယ်
  • loadDashboard က request နှစ်ခုကို Promise.all နဲ့ တစ်ပြိုင်နက် ပို့ရမယ်
  • ရလဒ်က { titles: string[], total: number } ဖြစ်ရမယ်
  • /broken ကို ခေါ်ပြီး error message ကို print ထုတ်ပါ
dashboard-data.ts
import express from "express";
import type { AddressInfo } from "node:net";

type Note = { id: string; title: string };
type Stats = { total: number };

// TODO: fetch the URL, throw "GET <path> failed with <status>" if not ok,
// otherwise return the parsed JSON as T
async function getJson<T>(url: string): Promise<T> {}

// TODO: load `${base}/notes` and `${base}/stats` in parallel
async function loadDashboard(base: string) {}

// Fake API: /notes, /stats and /broken (always 500)
const app = express();
app.get("/notes", (_req, res) => {
  res.json([{ id: "1", title: "Routing" }, { id: "2", title: "Caching" }]);
});
app.get("/stats", (_req, res) => {
  res.json({ total: 2 });
});
app.get("/broken", (_req, res) => {
  res.status(500).json({ error: "database is down" });
});

// TODO: listen on port 0, print loadDashboard(base), then the /broken error,
// then close the server

ရလဒ်: { titles: [ 'Routing', 'Caching' ], total: 2 } ကို print ထုတ်ပြီး နောက် line မှာ GET /broken failed with 500 ကို print ထုတ်ပါတယ်။ Server ကို close လုပ်လို့ program က ကိုယ်တိုင် ရပ်သွားပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

Path ကို ထုတ်ဖို့ new URL(url).pathname ကို သုံးပါ။ Server ရဲ့ port ကို (server.address() as AddressInfo).port ကနေ ယူပြီး base ကို http://127.0.0.1:<port> လို့ ဖွဲ့ပါ။

အဖြေ ကြည့်ရန်
dashboard-data.ts
import express from "express";
import type { AddressInfo } from "node:net";

type Note = { id: string; title: string };
type Stats = { total: number };

async function getJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`GET ${new URL(url).pathname} failed with ${response.status}`);
  }
  return (await response.json()) as T;
}

async function loadDashboard(base: string) {
  const [notes, stats] = await Promise.all([
    getJson<Note[]>(`${base}/notes`),
    getJson<Stats>(`${base}/stats`),
  ]);
  return { titles: notes.map((note) => note.title), total: stats.total };
}

const app = express();
app.get("/notes", (_req, res) => {
  res.json([{ id: "1", title: "Routing" }, { id: "2", title: "Caching" }]);
});
app.get("/stats", (_req, res) => {
  res.json({ total: 2 });
});
app.get("/broken", (_req, res) => {
  res.status(500).json({ error: "database is down" });
});

const server = app.listen(0, async () => {
  const { port } = server.address() as AddressInfo;
  const base = `http://127.0.0.1:${port}`;
  console.log(await loadDashboard(base));
  try {
    await getJson<Note[]>(`${base}/broken`);
  } catch (error) {
    console.log((error as Error).message);
  }
  server.close();
});

Quick Quiz 1 / 3

const res = await fetch(url) မှာ server က 404 ပြန်ရင် ဘာဖြစ်မလဲ?

Quick Quiz 2 / 3

getUser() က 1 စက္ကန့်၊ getPosts() က 2 စက္ကန့် ကြာပြီး တစ်ခုနဲ့တစ်ခု မမှီခိုပါဘူး။ ဘယ် version က 2 စက္ကန့်လောက်ပဲ ကြာမလဲ?

Quick Quiz 3 / 3

Server Component တစ်ခုက ကိုယ့် app ရဲ့ app/api/notes/route.ts ထဲက data ကို လိုချင်ပါတယ်။ အကောင်းဆုံး နည်းက ဘာလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Server Component ကို async လုပ်ပြီး fetch ဒါမှမဟုတ် database ကို render မလုပ်ခင် await လုပ်ပါ။
  • fetch က 404/500 မှာ reject မလုပ်လို့ response.ok ကို စစ်ပြီး throw လုပ်ပါ၊ error.tsx က ဖမ်းပါလိမ့်မယ်။
  • Next.js 15 ကစပြီး fetch ကို default အားဖြင့် cache မလုပ်ပါ၊ render တစ်ကြိမ်အတွင်း request တူတွေကိုတော့ memoize လုပ်ပါတယ်။
  • အမှီအခိုကင်းတဲ့ request တွေကို Promise.all နဲ့ ပို့ပြီး ကိုယ့် Route Handler ကို HTTP နဲ့ ပြန်မခေါ်ပါနဲ့။

Next.js — Fetching Data — Next.js

Next.js — Fetching Data — Next.js

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Server မှ Data Fetching | Thuta Learning