'How to set and append an array of objects in FireStore in JS / React JS

// sending contracts to user
export async function sendContractToOtherUser(email: string | any, contract: string) {
  try {

    let user : any = "";
    // search the users collection with the email and get the user id

    // Create a reference to the users collection
    const usersRef =  collection(db, "users");
    // Create a query against the collection.
    onSnapshot(usersRef, async(snapShot) => {
  
      snapShot.docs.forEach(doc => {
        if(doc.data().email === email) {
         user = doc.data();
        }} 
      );  
      console.log("//////user Found", user, typeof user, user.userID);

      // An Array which Contains an object
      const userContractData : any = [{
        userID : user.userID,
        contract: contract
      }];
      // setting the array 
      const newPendingContractRef : any = doc(db,"pendingContract", user.userID );
       await setDoc(newPendingContractRef,
        {...userContractData}
        , {merge: true});
      // console.log("/////////contract", pendingContract);

    });

  } catch (error) {
      console.log("/////////errror in sendContractToOtherUser", error);
  }
}

I want to append userContractData to the array present in the document (user.uid) of pendingContract collection. But what my code does that it only updates the already present data at 0th index. How can I structure my userContractData along with the setDoc method that I can append into the array

enter image description here



Solution 1:[1]

You are indeed setting value of first array item to the document. Try using arrayUnion() to push elements to an array:

await setDoc(newPendingContractRef,
        { contract: arrayUnion(...userContractData) }
        , {merge: true});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharmaraj