Home > database >  How to use onSnapshot in firebase? Can't work in my apps
How to use onSnapshot in firebase? Can't work in my apps

Time:11-12

I have made my own web apps(using vue.js) and using firestore as backend. In my firebase method, I tried to use onSnapshot method in firestore, but result was undefined.

firebase version is latest(v9).

so my code is below.

let user;
    const snapshot = await onSnapshot(collection(db, "user"), (snap: any) => {
      let user: any = [];
      snap.docs.forEach((doc: any) => {
        user.push({ ...doc.data() });
      });
      return user;
    });
    snapshot();
    console.log(user);

My firestore data is symple like below.

collection: user
documet: uid(automatically made by firebase)
data:{
 name:'someone name',
 age:22
}

so I was expected the result like that

{
 name:'someone name',
 age:22
}

but result was 'undefined' Does anyone give me advise, please?

CodePudding user response:

The onSnapshot function doesn't return a Promise, so you can't use await on it. What you're looking for is getDoc:

const snap = await getDocs(collection(db, "user"));
let user: any = [];
snap.docs.forEach((doc: any) => {
  user.push({ ...doc.data() });
});
console.log(user);

Also see the Firebase documentation on getting a document once.

  • Related