Thuta Learning
Firebase Tutorial
IntermediateDevOps & Toolsအလယ်အလတ်

Data ကို Realtime ဖတ်ခြင်း

Firebase Tutorialသင်ခန်းစာ 16

Data ကို Realtime ဖတ်ခြင်း

onSnapshot က Firestore data ပြောင်းလဲမှုကို realtime နားထောင်ပေးပါတယ်။ Chat message, live dashboard, collaborative notes, order status update တို့အတွက် အလွန်အသုံးဝင်ပါတယ်။

Code Example — Notes list realtime

javascript
import { getFirestore, collection, query, where, orderBy, onSnapshot } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

const db = getFirestore();
const auth = getAuth();

function listenMyNotes(renderNotes) {
  const user = auth.currentUser;
  if (!user) return () => {};

  const q = query(
    collection(db, 'notes'),
    where('ownerId', '==', user.uid),
    orderBy('createdAt', 'desc')
  );

  const unsubscribe = onSnapshot(q, (snapshot) => {
    const notes = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data()
    }));

    renderNotes(notes);
  });

  return unsubscribe;
}

ဒီ code က ဘာလုပ်တာလဲ?

Login user ပိုင်တဲ့ notes တွေကို created time အလိုက်ဖတ်ပြီး data ပြောင်းတာနဲ့ renderNotes function ကိုပြန်ခေါ်ပါတယ်။ UI မှာ refresh ခလုတ်မနှိပ်ဘဲ data update မြင်ရနိုင်ပါတယ်။

Common mistake

Realtime listener ကို မလိုတော့တဲ့အခါ unsubscribe() မလုပ်ရင် listener ဆက်နားထောင်နေပြီး performance ထိနိုင်ပါတယ်။ Single-page app တွေမှာ page/component ပြောင်းတဲ့အချိန် cleanup လုပ်ပါ။

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

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

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

Data ကို Realtime ဖတ်ခြင်း | Thuta Learning