Thuta Learning
React
ExercisesWeb Developmentအလယ်အလတ်

Practice: Hooks & Data

Reactသင်ခန်းစာ 3350 မိနစ်

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

  • useEffect ထဲမှာ async function သီးသန့် ရေးပြီး loading/error/data state သုံးခုနဲ့ fetch ကို ကိုင်တွယ်နိုင်ဖို့
  • res.ok ကို စစ်ပြီး ignore flag cleanup နဲ့ response အဟောင်းကို ပယ်နိုင်ဖို့
  • createContext/Provider/useContext နဲ့ props မပို့ဘဲ အဆင့်နှစ်ဆင့် အောက်ကို value ရောက်အောင် လုပ်နိုင်ဖို့
  • Custom hook က logic ကို မျှဝေပြီး state ကို မမျှဝေကြောင်း၊ useParams က string ပြန်ပေးကြောင်း ရှင်းပြနိုင်ဖို့

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

ရိုးရိုးလေး ရှင်းရရင်

ဒီလေ့ကျင့်ခန်းက Core Concepts practice ထက် တစ်ဆင့်ပိုခက်ပါတယ်။ Intermediate နဲ့ Advanced chapter မှာ သင်ခဲ့တဲ့ useEffect၊ useContext၊ custom hook၊ data fetching နဲ့ React Router ကို ပေါင်းသုံးရပါမယ်။ လက်တွေ့ app တိုင်းမှာ နေ့တိုင်းလိုလို တွေ့ရမယ့် ပုံစံတွေပါ။

Task လေးခု ရှိပါတယ်။ Task 1 က API ကနေ user list ကို loading state နဲ့အတူ ပြတာ၊ Task 2 က light/dark theme ကို Context နဲ့ အဆင့်နှစ်ဆင့် အောက်က component ဆီ ပို့တာ၊ Task 3 က modal ဖွင့်/ပိတ်၊ sidebar ပြ/ဖျောက် လို နေရာတွေမှာ သုံးမယ့် useToggle hook ရေးတာ၊ Task 4 က /users/:id route ကနေ id ကို ဖတ်ပြတာပါ။ ဖြေဆိုချက်ကို မကြည့်ခင် ကိုယ်တိုင် အရင်ကြိုးစားပါ။

Problem → Why → Solution

ပြဿနာ: Happy path မှာပဲ အလုပ်လုပ်တဲ့ fetch

Task 1 ရဲ့ ပထမ ကြိုးစားမှု အများစုက ဒီလိုပါ။ Wi-Fi ကောင်းပြီး API အလုပ်လုပ်နေရင် user list ပေါ်လာလို့ ပြီးပြီလို့ ထင်ရပါတယ်။ ဒါပေမယ့် console ထဲမှာ effect က cleanup function ကလွဲရင် ဘာမှ return မလုပ်ရဘူးဆိုတဲ့ warning ပေါ်နေပါတယ်။

URL ကို /userz လို့ typo ရေးမိရင် server က 404 နဲ့ {} ကို ပြန်ပို့ပြီး fetch က error မပစ်ပါဘူး။ setUsers({}) ဖြစ်သွားလို့ users.map is not a function ဆိုပြီး app ပျက်ပါတယ်။ Network လုံးဝ ပြတ်နေရင်တော့ fetch က reject ဖြစ်ပြီး setLoading(false) ကို ဘယ်တော့မှ မရောက်လို့ "Loading..." က ထာဝရ ကျန်နေပါတယ်။

UserList.jsx (first try)
useEffect(async () => {
  // an async callback returns a Promise, but React expects a cleanup function
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  setUsers(await res.json()); // a 404 body like {} is stored too
  setLoading(false);          // never reached if fetch rejects
}, []);

ဘာတွေ လွဲနေတာလဲ

async function က အမြဲ Promise ပြန်ပေးပြီး React ကတော့ effect ကနေ undefined ဒါမှမဟုတ် cleanup function ကိုပဲ မျှော်လင့်ပါတယ်။ fetch က network error မှာပဲ reject ဖြစ်ပြီး 404/500 ကို အောင်မြင်တဲ့ response အဖြစ် ပြန်ပေးလို့ res.ok ကို ကိုယ်တိုင်စစ်ရပါတယ်။ Error ဖြစ်ဖြစ်၊ မဖြစ်ဖြစ် loading ကို ပိတ်ဖို့ finally လိုပါတယ်။

Core concept: hook လေးခုနဲ့ ထောင်ချောက် လေးခု

Task တစ်ခုစီက hook တစ်ခုကို လေ့ကျင့်ပေးပြီး တစ်ခုစီမှာ မသိရင် ကျလေ့ရှိတဲ့ ထောင်ချောက် တစ်ခုစီ ရှိပါတယ်။ ကိုယ်ရေးထားတဲ့ code ကို ဒီအချက်လေးချက်နဲ့ တိုက်စစ်ပါ။

၁။ Effect ထဲက fetch (Task 1)

Effect callback ကို ရိုးရိုး function အဖြစ်ထားပြီး အထဲမှာ async function loadUsers ကို ကြေညာကာ ချက်ချင်း ခေါ်ပါ။ try ထဲမှာ res.ok ကို စစ်၊ catch ထဲမှာ error ကို state ထဲထည့်၊ finally ထဲမှာ loading ကို ပိတ်ပါ။ [] dependency ကြောင့် mount ပြီးချိန်မှာ run ပါတယ်။ Development ရဲ့ StrictMode က effect ကို နှစ်ခါ run လို့ ignore flag cleanup က အဲဒီ case ကိုပါ လုံခြုံစေပါတယ်။

၂။ Context နဲ့ အဆင့်ကျော် ပို့ခြင်း (Task 2)

createContext("light") က default value ပါတဲ့ context ကို ဆောက်ပါတယ်။ Provider က value ကို သူ့အောက်က tree တစ်ခုလုံးဆီ ပေးပြီး useContext က အနီးဆုံး Provider ရဲ့ value ကို ဖတ်ပါတယ်။ ကြားထဲက Toolbar က theme prop ကို လုံးဝ မထိပါဘူး။ Provider အပြင်ဘက်မှာ render လုပ်ရင်တော့ default "light" ကို ရပါတယ်။

၃။ Custom hook က logic ကို မျှဝေ (Task 3)

useToggle က useState ကို ထုပ်ထားတဲ့ function ပါ။ Sidebar နဲ့ FaqItem က hook တစ်ခုတည်းကို ခေါ်ပေမယ့် ခေါ်တိုင်း state အသစ် ရလို့ တစ်ခုကို toggle လုပ်တာ နောက်တစ်ခုကို မထိခိုက်ပါဘူး။ State ကို တကယ် မျှဝေချင်ရင် Context ဒါမှမဟုတ် parent ဆီ state ကို ရွှေ့ရပါတယ်။

၄။ URL param က string (Task 4)

Route မှာ :id လို့ ရေးထားရင် useParams() ကနေ { id } လို့ နာမည်တူ destructure လုပ်ရပါတယ်။ /users/3 ဆိုရင် id က number 3 မဟုတ်ဘဲ string "3" ပါ။ Number id ရှိတဲ့ data နဲ့ နှိုင်းယှဉ်ချင်ရင် အရင် ပြောင်းပြီး မှန်/မမှန် စစ်ပါ။

ပထမအချက်ကို Node မှာ မြင်အောင် ကြည့်ရအောင်။ Effect callback က return ပြန်တဲ့ value ကို React က cleanup အဖြစ် သိမ်းပါတယ်။ async callback ကတော့ ဘာမှ return မရေးထားလည်း Promise တစ်ခု ပြန်ပေးပါတယ်။

effect-return-value.js
// What an effect callback returns is what React treats as the cleanup.
const asyncEffect = async () => {
  /* await fetch(...) */
};
const plainEffect = () => {
  let ignore = false;
  return () => {
    ignore = true;
  };
};

const fromAsync = asyncEffect();
const fromPlain = plainEffect();
console.log("async callback returns a Promise:", fromAsync instanceof Promise);
console.log("plain callback returns a function:", typeof fromPlain === "function");

// async callback returns a Promise: true
// plain callback returns a function: true
Mental model: hook တစ်ခုစီက မေးခွန်း တစ်ခုစီကို ဖြေ
  1. useEffect: render ပြီးမှ ဘာ sync လုပ်မလဲ
  2. useContext: အပေါ်က ဘာ value ပေးထားလဲ
  3. Custom hook: ဒီ logic ကို ဘယ်မှာ ပြန်သုံး
  4. useParams: URL က ဘာပြောနေလဲ

ဘယ် hook ကို သုံးရမလဲ မသေချာရင် ဒီမေးခွန်းလေးခုထဲက ဘယ်ဟာကို ဖြေချင်တာလဲ အရင်မေးပါ။

အခြေခံ ပုံစံ

jsx
useEffect(() => {
  let ignore = false;
  async function load() {
    try { const data = await getData(); if (!ignore) setData(data); }
    catch (err) { if (!ignore) setError(err); }
    finally { if (!ignore) setLoading(false); }
  }
  load();
  return () => { ignore = true; };
}, [dependency]);

const value = useContext(SomeContext); // nearest Provider's value

Effect ထဲမှာ async function ကို ကြေညာပြီး ခေါ်၊ try/catch/finally နဲ့ state သုံးခုကို set လုပ်ကာ cleanup က ignore flag ကို ဖွင့်ပါတယ်။ Context value ကိုတော့ useContext တစ်ကြောင်းနဲ့ ဖတ်ပါတယ်။

ဖြေဆိုချက်များ: Task ၁ ကနေ ၄ အထိ

ကိုယ်တိုင်ရေးပြီးမှ နှိုင်းယှဉ်ပါ။ File တွေကို comment နဲ့ ခွဲထားပါတယ်။ Task 4 အတွက် react-router-dom ကို install လုပ်ပြီး App ကို <BrowserRouter> နဲ့ ထုပ်ထားဖို့ လိုပါတယ်။ Task 1 မှာ error state ကိုပါ ထည့်ထားတာက original task ရဲ့ "5 မိနစ် extension" ကို ဖြေထားတာပါ။

src (4 tasks)
// Task 1 - src/components/UserList.jsx
import { useEffect, useState } from "react";

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let ignore = false;

    async function loadUsers() {
      try {
        const res = await fetch("https://jsonplaceholder.typicode.com/users");
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        if (!ignore) setUsers(data);
      } catch (err) {
        if (!ignore) setError(err.message);
      } finally {
        if (!ignore) setLoading(false);
      }
    }

    loadUsers();
    return () => {
      ignore = true;
    };
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p role="alert">Could not load users: {error}</p>;
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;

// Task 2 - src/theme.jsx
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

function ThemeBadge() {
  const theme = useContext(ThemeContext);
  return <span className={`badge badge-${theme}`}>Theme: {theme}</span>;
}

function Toolbar() {
  return (
    <div className="toolbar">
      <ThemeBadge />
    </div>
  );
}

export function ThemeApp() {
  const [theme, setTheme] = useState("light");
  const nextTheme = theme === "light" ? "dark" : "light";

  return (
    <ThemeContext.Provider value={theme}>
      <button type="button" onClick={() => setTheme(nextTheme)}>
        Switch to {nextTheme}
      </button>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// Task 3 - src/hooks/useToggle.js
import { useState } from "react";

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue((v) => !v);
  return [value, toggle];
}

export default useToggle;

// Task 3 usage - two components, two independent states
function Sidebar() {
  const [open, toggleOpen] = useToggle(true);
  return (
    <aside>
      <button type="button" onClick={toggleOpen}>{open ? "Hide" : "Show"} menu</button>
      {open && <nav>Menu links</nav>}
    </aside>
  );
}

function FaqItem() {
  const [expanded, toggleExpanded] = useToggle();
  return (
    <div>
      <button type="button" aria-expanded={expanded} onClick={toggleExpanded}>
        What is a hook?
      </button>
      {expanded && <p>A function that starts with use.</p>}
    </div>
  );
}

// Task 4 - src/components/UserDetail.jsx
// route: <Route path="/users/:id" element={<UserDetail />} />
import { useParams } from "react-router-dom";

function UserDetail() {
  const { id } = useParams();
  return <h3>User Detail: {id}</h3>;
}

export default UserDetail;

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Ignore flag for stale responseslet ignore = false;

    Effect run တစ်ကြိမ်စီမှာ သီးသန့် flag ရှိပါတယ်။ Cleanup က true လုပ်လိုက်ရင် နောက်မှ ရောက်လာတဲ့ response က state ကို မထိတော့ပါဘူး။

  2. HTTP errors become real errorsif (!res.ok) throw new Error(`HTTP ${res.status}`);

    404/500 ကို fetch က error အဖြစ် မမြင်လို့ ကိုယ်တိုင် throw လုပ်ပြီး catch block ဆီ ပို့ပါတယ်။

  3. Loading always endsif (!ignore) setLoading(false);

    finally ထဲမှာ ရှိလို့ အောင်မြင်သည်ဖြစ်စေ၊ error ဖြစ်သည်ဖြစ်စေ "Loading..." က ပျောက်ပါတယ်။

  4. Reading the nearest Providerconst theme = useContext(ThemeContext);

    ThemeBadge က Toolbar ထဲမှာ ရှိပေမယ့် prop မလိုဘဲ ThemeApp ရဲ့ Provider value ကို တိုက်ရိုက် ဖတ်ပါတယ်။ Theme ပြောင်းရင် ဒီ component က re-render ဖြစ်ပါတယ်။

  5. Hook returns a value and an actionreturn [value, toggle];

    useState လို array ပြန်ပေးလို့ ခေါ်တဲ့သူက [open, toggleOpen]၊ [expanded, toggleExpanded] လို နာမည်ကြိုက်ပေးနိုင်ပါတယ်။

  6. Param name matches the routeconst { id } = useParams();

    Route ထဲက :id နဲ့ နာမည်တူမှ value ရပါတယ်။ ရလာတဲ့ id က string ဖြစ်ပါတယ်။

You should see
UserList က "Loading..." ကို အရင်ပြပြီး data ရောက်တာနဲ့ user နာမည် list ကို ပြပါတယ်။ Request မအောင်မြင်ရင် "Could not load users: ..." ပြပါတယ်။ Theme badge က "Theme: light" ကနေ button နှိပ်တိုင်း dark/light ပြောင်းပြီး Sidebar နဲ့ FAQ က တစ်ခုနဲ့တစ်ခု မသက်ဆိုင်ဘဲ ဖွင့်/ပိတ် ဖြစ်ပါတယ်။ /users/3 မှာ "User Detail: 3" ပေါ်ပါတယ်။

Ignore flag က ဘာကို ကာကွယ်လဲ

Task 1 မှာ dependency က [] ဖြစ်လို့ race ဖြစ်ခွင့် နည်းပါတယ်။ ဒါပေမယ့် [userId] လို dependency ရှိတဲ့ effect မှာ user က user 1 ကနေ user 2 ကို မြန်မြန်ပြောင်းရင် request နှစ်ခု ပြိုင်သွားပါတယ်။ ပထမ request က နှေးလို့ နောက်မှ ရောက်လာရင် screen ပေါ်မှာ user 1 ကို ပြနေပါလိမ့်မယ်။ React က effect အသစ် မ run ခင် အဟောင်းရဲ့ cleanup ကို run လို့ ignore flag က response အဟောင်းကို ပယ်ပါတယ်။

အောက်က code က setTimeout နဲ့ ဒီ race ကို model လုပ်ထားတာပါ။

race-model.mjs
// Two requests for different users; the first one is slower and finishes last.
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fakeFetchUser = (id) => delay(id === 1 ? 30 : 10, { id, name: `User ${id}` });

async function run(useIgnoreFlag) {
  let shown = "(nothing yet)";
  let cleanupPrevious = () => {};

  for (const id of [1, 2]) {
    cleanupPrevious(); // React runs the old effect's cleanup before the next one
    let ignore = false;
    fakeFetchUser(id).then((user) => {
      if (!useIgnoreFlag || !ignore) shown = user.name;
    });
    cleanupPrevious = () => {
      ignore = true;
    };
  }

  await delay(50);
  console.log(useIgnoreFlag ? "with ignore flag:   " : "without ignore flag:", shown);
}

await run(false);
await run(true);

// without ignore flag: User 1
// with ignore flag:    User 2

Provider ရေးပုံ နှစ်မျိုး

ဒီ tutorial က <ThemeContext.Provider value={theme}> ကို သုံးပါတယ်။ React 19 မှာ <ThemeContext value={theme}> လို့ ပိုတိုတိုရေးလို့လည်း ရပါတယ်။ Project ရဲ့ React version ကို ကြည့်ပြီး တစ်မျိုးတည်းကို တသမတ်တည်း သုံးပါ။

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

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

ဒီ task လေးခုက real app တစ်ခုရဲ့ အရိုးစုပါပဲ။ Product list page က data fetch လုပ်ပြီး product detail page က /products/:id ကနေ id ဖတ်ပါတယ်။ Theme၊ login ဝင်ထားတဲ့ user၊ ဘာသာစကား ရွေးချယ်မှုလို app တစ်ခုလုံး သိဖို့လိုတဲ့ value တွေကို Context နဲ့ ပို့ပြီး modal၊ dropdown၊ accordion တွေက useToggle လို hook သေးသေးလေးတွေကို မျှဝေသုံးပါတယ်။

Production မှာတော့ fetch-in-effect ကို ကိုယ်တိုင် ရေးမယ့်အစား TanStack Query၊ SWR လို library ဒါမှမဟုတ် framework ရဲ့ data loading (React Router ရဲ့ loader၊ Next.js ရဲ့ Server Component) ကို သုံးလေ့ရှိပါတယ်။ Cache၊ retry၊ race handling တွေကို အဆင်သင့် ပေးလို့ပါ။ ဒါပေမယ့် loading/error/data သုံးခု၊ res.ok စစ်တာ၊ response အဟောင်း ပယ်တာ ဆိုတဲ့ အယူအဆတွေက အဲဒီ tool တွေ အောက်ခြေမှာ အတူတူပါပဲ။

အမှားများ

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

useEffect(async () => ...) လို့ ရေးတာ

Callback က Promise ပြန်ပေးလို့ React က console မှာ warning ပြပြီး cleanup function ပြန်ပေးလို့ မရတော့ပါဘူး။ Effect ထဲမှာ async function ကို သီးသန့် ကြေညာပြီး ခေါ်ပါ၊ cleanup ကို effect ကနေ return လုပ်ပါ။

Custom hook က state ကို မျှဝေတယ်လို့ ထင်တာ

Header နဲ့ Sidebar နှစ်ခုလုံးက useToggle() ကို ခေါ်ရင် တစ်ခုက ဖွင့်လိုက်ရင် နောက်တစ်ခုပါ ပွင့်မယ်လို့ မျှော်လင့်တတ်ပါတယ်။ Hook ခေါ်တိုင်း state သီးသန့် ရလို့ မဖြစ်ပါဘူး။ State တစ်ခုတည်းကို မျှဝေချင်ရင် common parent ဆီ ရွှေ့ပါ ဒါမှမဟုတ် Context ကို သုံးပါ။

URL param ကို number နဲ့ တိုက်ရိုက် နှိုင်းယှဉ်တာ

users.find((u) => u.id === id) က id "3" (string) နဲ့ 3 (number) မတူလို့ undefined ပြန်ပေးပြီး "User not found" ကို အမြဲပြပါတယ်။ Number(id) နဲ့ ပြောင်းပြီး "abc" လို မမှန်တဲ့ value ကိုလည်း စစ်ပါ။

Best Practices

ဒီလေ့ကျင့်ခန်းကို ပိုအကျိုးရှိအောင်

  • DevTools ရဲ့ Network tab မှာ "Offline" နဲ့ "Slow 3G" ကို ရွေးပြီး Task 1 ရဲ့ loading နဲ့ error state ကို ကိုယ့်မျက်စိနဲ့ စစ်ပါ
  • URL ကို တမင် မှားရေးပြီး 404 မှာ error message ပေါ်လား၊ app ပျက်လား ကြည့်ပါ
  • ThemeBadge ကို Provider အပြင်ဘက်မှာ တစ်ခါ render လုပ်ကြည့်ပြီး default value ကို မြင်အောင် လုပ်ပါ
  • /users/abc ကို ဖွင့်ကြည့်ပြီး မမှန်တဲ့ id ကို ဘယ်လို ပြမလဲ ဆုံးဖြတ်ပါ

Mini challenge

Fetch logic ကို test လုပ်လို့ရအောင် ခွဲထုတ်ပါ

Task 1 နဲ့ Task 4 ရဲ့ logic ကို component အပြင်ကို ထုတ်ပါမယ်။ loadUsers(fetchImpl, url) က fetch function ကို argument အဖြစ် လက်ခံလို့ network မလိုဘဲ fake fetch တွေနဲ့ အောင်မြင်တာ၊ 404၊ offline ဆိုတဲ့ case သုံးခုလုံးကို Node မှာ စမ်းနိုင်ပါတယ်။ parseUserId(param) က useParams ကနေ ရတဲ့ string ကို စစ်ဆေးပြီး number ပြောင်းပေးပါတယ်။

  • loadUsers က { status, users, error } object ကို အမြဲ ပြန်ပေးပြီး ဘယ်တော့မှ throw မလုပ်ရပါ
  • res.ok false ဖြစ်ရင် "HTTP <status>" error အဖြစ် သတ်မှတ်ပါ
  • fetchImpl က reject ဖြစ်ရင် err.message ကို error အဖြစ် ထည့်ပါ
  • parseUserId က "3" လို အပေါင်း integer string အတွက် number၊ "abc"၊ "-1"၊ "0"၊ undefined အတွက် null ပြန်ပေးပါ
users-logic.mjs
async function loadUsers(fetchImpl, url) {
  // TODO: call fetchImpl(url); throw on !res.ok; parse JSON
  // TODO: return { status: "success", users, error: null }
  // TODO: on any error return { status: "error", users: [], error: message }
}

function parseUserId(param) {
  // TODO: accept only digit strings, convert with Number, reject 0
}

// TODO: three fake fetch functions: one ok, one 404, one that rejects
// TODO: print the result of loadUsers for each, then parseUserId for
//       "3", "007", "abc", "-1", "0" and undefined

ရလဒ်: ok case က success နဲ့ user နာမည်နှစ်ခု၊ 404 case က "HTTP 404"၊ offline case က "Failed to fetch" ပြပါမယ်။ parseUserId က "3" အတွက် 3၊ "007" အတွက် 7၊ ကျန်တာ အားလုံးအတွက် null ပြန်ပေးပါမယ်။

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

Fake fetch က { ok, status, json: async () => data } ပုံစံ object ကို ပြန်ပေးရုံပါပဲ။ Offline case အတွက် async () => { throw new Error("Failed to fetch"); } လို့ ရေးပါ။ Digit သက်သက် ဟုတ်/မဟုတ် /^\d+$/ နဲ့ စစ်နိုင်ပါတယ်။ Component ထဲမှာ const result = await loadUsers(fetch, url) လို့ ခေါ်ပြီး state သုံးခုကို set လုပ်ပါ။

အဖြေ ကြည့်ရန်
users-logic.mjs
async function loadUsers(fetchImpl, url) {
  try {
    const res = await fetchImpl(url);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const users = await res.json();
    return { status: "success", users, error: null };
  } catch (err) {
    return { status: "error", users: [], error: err.message };
  }
}

function parseUserId(param) {
  if (!/^\d+$/.test(param ?? "")) return null;
  const id = Number(param);
  return id > 0 ? id : null;
}

const okFetch = async () => ({
  ok: true,
  status: 200,
  json: async () => [
    { id: 1, name: "Aung Aung" },
    { id: 2, name: "Su Su" },
  ],
});
const notFoundFetch = async () => ({ ok: false, status: 404, json: async () => ({}) });
const offlineFetch = async () => {
  throw new Error("Failed to fetch");
};

const url = "https://example.com/users";
const cases = [["ok", okFetch], ["404", notFoundFetch], ["offline", offlineFetch]];
for (const [label, impl] of cases) {
  const result = await loadUsers(impl, url);
  const names = result.users.map((user) => user.name).join(", ") || "-";
  const error = result.error ?? "-";
  console.log(`${label}: ${result.status} | users: ${names} | error: ${error}`);
}

for (const param of ["3", "007", "abc", "-1", "0", undefined]) {
  const shown = param === undefined ? "undefined" : JSON.stringify(param);
  console.log(`useParams id ${shown} -> ${parseUserId(param)}`);
}

Quick Quiz 1 / 3

Sidebar နဲ့ FaqItem နှစ်ခုလုံးက useToggle() ကို ခေါ်ထားတယ်။ Sidebar ရဲ့ button ကို နှိပ်ရင် FaqItem ဘာဖြစ်မလဲ။

Quick Quiz 2 / 3

Route က /users/:id ဖြစ်ပြီး URL က /users/3 ပါ။ const { id } = useParams(); ပြီးရင် users.find((u) => u.id === id) (u.id တွေက number) က ဘာပြန်ပေးမလဲ။

Quick Quiz 3 / 3

const ThemeContext = createContext("light"); ရှိပြီး ThemeBadge ကို Provider အပြင်ဘက်မှာ render လုပ်ရင် ဘာပြမလဲ။

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

  • Effect callback ကို async မလုပ်ပါနဲ့၊ အထဲမှာ async function ကြေညာပြီး ခေါ်ကာ cleanup ကို return ပြန်ပါ
  • res.ok စစ်၊ catch မှာ error သိမ်း၊ finally မှာ loading ပိတ်၊ ignore flag နဲ့ response အဟောင်း ပယ်ပါ
  • Context က Provider အောက်က component တိုင်းဆီ props မပါဘဲ value ပို့ပြီး Provider မရှိရင် default ကို ရပါတယ်
  • Custom hook က logic ကို မျှဝေပြီး state ကို မမျှဝေပါ၊ useParams က string ပြန်ပေးလို့ ပြောင်းပြီး စစ်ပါ

React Documentation — React

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

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

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

Practice: Hooks & Data | Thuta Learning