နားလည်ထားရမယ့် အချက်
Apollo Client က React hooks (`useQuery`, `useMutation`) ဖြင့် GraphQL data ကို component ထဲ fetch/update လုပ်ဖို့ ပေးပါတယ်—loading/error/data states ကို hook တစ်ခုတည်းက manage လုပ်ပေးပါတယ်။ InMemoryCache က response objects များကို `__typename` + `id` ဖြင့် normalize လုပ်ပြီးသိမ်းထားလို့ query နှစ်ခု တူညီ object တစ်ခုကို ပြန်ဖတ်ရင် cache တစ်ခုတည်းက data ကို share ပေးပါတယ်—mutation တစ်ခုက object ကို update လုပ်ရင် screen တွေအားလုံး automatically sync ဖြစ်သွားနိုင်ပါတယ်။
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
Tutorial Platform blog frontend ကို `GET_POSTS` query ကို `useQuery` ဖြင့် fetch လုပ်ပြီး `PostList` component ဆောက်မယ်။ `ADD_COMMENT` mutation ကို `useMutation` ဖြင့် ခေါ်ပြီး success ပြီးနောက် `refetchQueries` သို့ cache update function ဖြင့် post list ကို automatically refresh စေမယ်။
အတူတူ စမ်းရေးကြည့်မယ်
const GET_TUTORIALS = gql`
query GetTutorials {
tutorials {
id
title
}
}
`;
function TutorialList() {
const { data, loading, error } = useQuery(GET_TUTORIALS);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<ul>
{data.tutorials.map((t: { id: string; title: string }) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
);
}React component ထဲမှာ `useQuery` ဖြင့် data ဖတ်ပြီး `useMutation` ဖြင့် write လုပ်နိုင်မည်။၅ မိနစ် စမ်းကြည့်
`ADD_COMMENT` mutation ကို `useMutation` ဖြင့် ခေါ်ပြီး loading state ကို submit button disable အဖြစ် ချိတ်ဆက်ပါ။
သတိလေးတစ်ချက်
Object တစ်ခုမှာ `id` field ကို query ထဲမထည့်ဘဲ ချန်ထားရင် InMemoryCache က ဒီ object ကို normalize မလုပ်နိုင်တော့ဘဲ cache miss/duplicate data ပြဿနာဖြစ်နိုင်ပါတယ်—`id` ကို query တိုင်းမှာ ထည့်ပါ။
Apollo Client — Get Started — GraphQL