Home > OS >  How Do I Set Doc Without Overwriting Array In Firestore React
How Do I Set Doc Without Overwriting Array In Firestore React

Time:09-30

I'm building a to-do style app in react. I'm using firebase/firestore for my data. My users collection and document look like this:

enter image description here

Here's my createLabel function:

const createLabel = async () => {
  setDoc(doc(db, "users", currentUser.uid), {
    labels: { ...labels, id: fifa },
  });
};

This function basically erases everything in thing in the labels collection and adds only id:fifa like so:

enter image description here

I'm wondering how I can somehow save a copy of the current collection, and re-write it with a new object (2) that would contain cards: [{}] and id:"fifa" ?

I saved the entire labels array into state called labels and tried to use the spread operator to push the new id:fifa into the labels array but I'm not getting it where I need it to be.

Any help in achieving this would be appreciated.

CodePudding user response:

As Doug alluded to in his comments, you'll want to do:

setDoc(doc(db, "users", currentUser.uid), {
  labels: arrayUnion({ id: fifa })
}, { merge: true })

Here:

  • arrayUnion ensures that your values get merged with the existing items in the labels field. Note that this only adds the item if the exact same value isn't in the array yet.
  • { merge: true } ensures that the other fields don't get overwritten either.
  • Related