2

I'm trying to remove a map item from an array in firebase. From what I understand with firebase - you are unable to delete the item based on the index. Should I structure this a different way or is there an easier way to remove a specific object from the array? Thank you

Error: 'No document to update: '

enter image description here

  const listingRef = doc(db, 'users', 'savedListings');

  const deleteListing = async () => {
    try {
      await updateDoc(listingRef, {
        savedListings: deleteField()
      });
    } catch (e) {
      console.log(e.message);
    }
  };```
1
  • hi, i need help in creating react array map in firebase, can you please share source code for this. i am trying for the past 3 months but can't understand it. Commented Aug 1, 2022 at 5:39

1 Answer 1

1

The doc() takes path to a document that should be users/[email protected] in this case. While you can use arrayRemove() to remove elements from an array field you cannot delete an object from an array unless you know the exact value that object including all the fields.

const listingRef = doc(db, 'users', 'USER_EMAIL'); // USER_EMAIL is document ID

const deleteListing = async () => {
  try {
    await updateDoc(listingRef, {
      savedListings: arrayRemove("THAT_OBJECT")
    });
  } catch (e) {
    console.log(e.message);
  }
};

If you don't have that exact object, then you'll have to read the document, manually remove the element from array and update the document back.

Sign up to request clarification or add additional context in comments.

5 Comments

If I pass in the ${user.email} I can delete the entire array which is not optimal. Would I be better off not using an array to store this data perhaps?
@ClintBriley an array seems ideal to store user's addresses. Just to delete a specific one from that array, you would have to use either of the methods mentioned in my answer - fetching the document, removing the address and updating back the modified array or use arrayRemove() if you have that address object on client side.
If I were trying to remove the entire map within the array would I run the "arrayRemove()" on each "address" "beds" "baths" "price" etc..?
@ClintBriley you'll need to know exact value of that map e.g. arrayRemove({ address: "", beds: 4, ...exactValueOfOtherFields })
If I only want to delete the object from my array and never update fields within my object, do I still need to remove every field from within that specific object? Not sure what the best way to go about this is. Seems like a pain to not be able to delete the object based off the index. Thank you 🙏

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.