Thuta Learning
ရှာဖွေရန်
IntermediateDevOps & Toolsintermediate

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

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

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 လုပ်ပါ။

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