0

I'm trying to create a function that will add to the labels array. The desired functionality for my createCard function is:

  1. Read the firestore data
  2. Modify the labels array with the new card info
  3. Write the labels array back to firestore

I believe this is the correct way to add to an object inside an array in firestore. Here's my code:

This is where I get my data from firestore. I setLabel() as you can see to hold all the data in state.

const getData = async () => {
    const querySnapshot = await getDoc(doc(db, "users", currentUser.uid));
    setLabels(querySnapshot.data());
    console.log("Data: ", labels);
};

Here is my function that should add data to the labels collection. I'm trying to modify the labels array and write back to firestore with the updated data.

  const createCard = async (name, tags) => {
    // READ FIRESOTRE DOC
    const querySnapshot = await getDoc(doc(db, "users", currentUser.uid));
    // MODIFY LABELS ARRAY IN FRONT-END
    const newCard = labels.labels[activeLabel].cards.push({
      name: name,
      tags: tags,
    });
    // WRITE MODIFIED ARRAY BACK TO FIRESTORE
    await updateDoc(
      doc(db, "users", currentUser.uid),
      {
        labels: arrayUnion({ newCard }),
      },
      { merge: true }
    );
    // console.log(newCard);
    console.log(labels);
    getCards();
    console.log("Tags Created");
  };

The problem is my function currently ADDS a new object named newCard to the bottom, as pointed out with a red arrow:

enter image description here

The desired functionality would be to add a new card object {name: name, tags:tag} to one of the objects above that exists already. I have state that holds a number inside activeLabel, and that would be the desired set of cards to add to. So if I wanted to add the object where the top blue arrow (pictured below) points to, activeLabel = 0 because that's how I'm identifying which object to modify.

Please let me know if there's more information necessary to help with this problem. Thank you in advance for any tips or formatting help.

enter image description here

jakeycodez
  • 49
  • 2
  • 7
  • The only way to update an item in an array in Firestore is to: read the document and grab the array from it, update the item in the app, and then write the entire array back. arrayUnion won't work at all - it just adds a new item to an array. – Doug Stevenson Oct 10 '22 at 23:32
  • i outlined those three steps in my question. so i guess I’m just doing those steps wrong, and arrayUnion is the main thing that’s wrong. I should change my question to “how do I modify this array” – jakeycodez Oct 10 '22 at 23:52
  • Just read the document, modify the array in memory, then write the array back to the document. – Doug Stevenson Oct 11 '22 at 00:13
  • Now I'm really embarrassed because that's what I was trying above in my creatCard function. I'll keep working at it. Thanks Doug! – jakeycodez Oct 11 '22 at 00:18

0 Answers0