I'm trying to create a function that will add to the labels array. The desired functionality for my createCard function is:
- Read the firestore data
- Modify the labels array with the new card info
- 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:
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.