Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot get fields from SnapShot in firebase

I’m trying to get the real-time document fields (text and timeStamp) to be displayed from the "first" collection in firestore collection, with the use of onSnapshot. I can verify that the snapshot realtime updation is working, on addition of a new document, it does shows an update. But I cannot access the text and timeStamp in the document.

onSnapshot(collection(db, 'first'), (snapshot) => {
        console.log(snapshot.text, snapshot.timeStamp);
      });

It just shows undefined to me. Also, I just want to access this database, db only when the user is authenticated. So is there a way to check if the user is authenticated?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To get the data from a document snapshot, you need to call data() on it. In addition, since you’re reading an entire collection, you get back a query snapshot that can contain multiple documents, which you also need to handle.

So:

onSnapshot(collection(db, 'first'), (querySnapshot) => {
  querySnapshot.docs.forEach((docSnapshot) => {
    console.log(docSnapshot.data().text, docSnapshot.data().timeStamp);
  })
});

See the documentation on getting data from Firestore and on reading all documents from a collection for more examples like this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading