简体   繁体   中英

Firestore issue with creating multiple documents

So,I am working on a react native application. In this application, I want to send a message to multiple users using firestore. Basically,I am trying to create multiple documents generated from other documents. The issue is that only one document is created. This is the code used to create the documents:

 Userref.where("Groupe","array-contains","/Roles/"+email+"/") 
        .onSnapshot((querySnapshot) => {
          querySnapshot.forEach((da) => {
              const batch = db.batch();
              setMesid(uuid.v4());
              const messageRef = db.collection("Messagerecieved").doc(mesid)
              batch.set(messageRef,{
                reciever:da.data().uid,
                sender:auth.currentUser.uid,
                senderemail:auth.currentUser.email,
                subject:Sujet,
                message:Message,
                createdAt: new Date(),
                messageid: mesid,
                file:fileUrl,
      
            })
            
              batch.commit();
            });}) 

The expected result is to have multiple documents created under the collection Messagerecieved. But even if there are many documents satisfying the condition only one document is created.

I suspect that setMesid is a useState hook, and those execute asynchronously.

So instead of trying to read it from the hook, just use a local variable to keep it:

const batch = db.batch();
const messageID = uuid.v4();
const messageRef = db.collection("Messagerecieved").doc(messageID)
setMesid(messageID); // 👈 this is only needed if you want to show it in the UI too

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