简体   繁体   中英

When data is added to the firestore, I want to listen with onSnapshot so that the data can be called automatically, but I don't know how to use

I want to listen for the value of message in the data structure in the attached image

I get an error with this code

secondDb.collection("chats")
  .doc(dockey)
  .onSnapshot(function (doc) {
    doc.docChanges().forEach(function (change) {
      if (change.type === "added") {
        console.log(doc.data().messages[0]);
      } else if (change.type === "modified") {
        // 
      } else if (change.type === "removed") {
        // 
      }
    })
  });

error code doc.docChanges is not a function

The data structure is as follows: 数据结构

You can access the data over the collection you want to retrieve

var unsubscribe = firestore().collection('chats').onSnapshot(snapshot =>{
  snapshot .docChanges().map((change) => {
   if (change.type === "added") {
    console.log(doc.data().messages[0]);
   } else if (change.type === "modified") {
     // 
   } else if (change.type === "removed") {
     // 
   }
  })
})

Looking at your data structure, I would say that you probably don't want to call .onSnapshot on your entire collection.

Your initial code was fine. But, since you called .onSnapshot on a DocumentReference, you got a DocumentSnapshot . Instead of .docChanges you would just do doc.data().messages .

You should also check out the documentation on Best Practices for realtime updates.

If you're trying to make a realtime messaging app, you might consider using Firebase Cloud Messaging instead of onSnapshot . You could load all the messages for a conversation from Firestore when a user opens the app, and receive any new ones using FCM as long as the user is connected to the internet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM