0

I'm trying to make a button that can edit an item within a documents array in firebase. Basically, the functionality I'm building is: you click an EDIT button, and it changes a

tag into an tag where you would make your edit/update to the array item. Then you would click a DONE button and the update to the array would happen. For some reason, I can only find documentation on firebase for updating a document, and not an item inside the array. I've tried using arrayUnion but it only adds a new item to the array. I'm trying to update the info[0].tags in the screenshot below. Please let me know if I'm missing information to help make this work.

My issue seems to be I can't do: info[i]: arrayUnion({tags: tags}) so I'm not sure how to tell the updateDoc function which item in the info array I need to update.

Here's the code:

  const editCard = async (tags, i) => {
    const fieldRef = doc(db, "labels", activeLabels);
    await updateDoc(fieldRef, {
      info[i]: arrayUnion({ tags: tags }),
    });
    console.log(tags);
    getLabels();
    findLabel(activeLabels);
    toast.success("Tags Updated!");
  };


[![firebase document and array][1]][1]


  [1]: https://i.stack.imgur.com/PDJcc.png
jakeycodez
  • 49
  • 2
  • 7
  • 1
    There is no way to update an existing item in an array in Firestore. You will have to: read the document, update the array in your application code, and then write the entire array back to the database. – Frank van Puffelen Aug 25 '22 at 22:27
  • Apologies, I'm a self-taught programmer and am a bit confused by the best way to proceed. When you say "Update the array in your application code", isn't that what I'm currently trying to do? I guess my mistake here is I'm trying to update an existing array - and you're saying to delete the array and re-make it with the new changes? Can you possibly provide me with some example code? I'm not asking for a blatant answer but just something I can rework or expand on to get my desired result. If not, thank you for the advice either way. – jakeycodez Aug 26 '22 at 00:01
  • https://cloud.google.com/firestore/docs/samples/firestore-data-set-array-operations is this the correct documentation to follow @FrankvanPuffelen? – jakeycodez Aug 26 '22 at 00:27
  • You're trying to update the item without reading the document (so step 2 without step 1) which isn't possible. I linked two questions that cover this in more detail, one with many more links to other questions about the same problem. – Frank van Puffelen Aug 26 '22 at 08:26

0 Answers0