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

Fetching Data

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

React app တွေမှာ API မှ data ယူပြီး UI ထဲပြတာ အရေးကြီးပါတယ်။ `useEffect` နဲ့ data fetching ကို component ပေါ်လာတဲ့အချိန် run စေပြီး `useState` နဲ့ loading/data/error state များကိုထိန်းနိုင်ပါတယ်။

jsx
import { useEffect, useState } from 'react';

function Post() {
  const [post, setPost] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    async function loadPost() {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
        if (!response.ok) throw new Error('Failed to load post');
        const data = await response.json();
        setPost(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    loadPost();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error}</p>;

  return <h1>{post.title}</h1>;
}

Component ပထမဆုံး render ဖြစ်ပြီးနောက် API ကိုခေါ်ပါတယ်။ Data ရရင် `post` state ထဲသိမ်း၊ error ဖြစ်ရင် `error` state ထဲသိမ်း၊ အဆုံးမှာ loading ကို false ပြောင်းပါတယ်။

You should see
အစမှာ Loading ပေါ်ပြီး data ရောက်လာရင် post title ပေါ်လာမယ်။ API ပြဿနာရှိရင် error message ပေါ်မယ်။

Info

Real project မှာ API URL, auth token, pagination, retry, caching စတာတွေပါလာနိုင်ပါတယ်။ အခြေခံ pattern ကတော့ loading/data/error ကိုရှင်းရှင်းထိန်းတာပါပဲ။

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

  • `fetch()` က network error မဟုတ်ရင် 404/500 ကို catch ထဲအလိုလိုမပို့ပါ။ `response.ok` ကိုစစ်ပါ။
Fetching Data | Thuta Learning