0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Maney
  • 1

1 Answers1

1

I suspect that setMesid is a useState hook, and those execute asynchronously. See useState set method not reflecting change immediately for more on this.

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

const batch = db.batch();
const messageID = uuid.v4(); // assign to a local var and use 
const messageRef = db.collection("Messagerecieved").doc(messageID)
setMesid(messageID); //  this is only needed if you want to show it in the UI too
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807