1

How to delete an element from array from firebase? I have two arrays - the first one with names and the second one with menu type. With my code, I deleted just from the first array.

  func reloadTableView() {
    guestList.removeAll()
    if let tableId = tableData?.id {
        
        Database.database().reference().child("userInfo").child(uid!).child("tables").child(tableId).child("guestsOnTable").queryOrderedByKey().observe(.value) { (snapshot) in
            if snapshot.childrenCount>0 {
                self.guestList.removeAll()
                
                for guest in snapshot.children.allObjects as![DataSnapshot]{
                    if let guestObject = guest.value as? String{
                        self.guestList.append(guestObject)
                    }
                }
                DispatchQueue.main.async {
                    self.guestsOnTableTableView.reloadData()
                }
            }
        }
        
    }
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        let guestName = guestList[indexPath.row]

        if let tableId = tableData?.id{
            refGuests = Database.database().reference().child("userInfo").child(uid!).child("tables").child(tableId).child("guestsOnTable")
            refGuests.observe(.value) { (snapshot, error) in

                if let error = error {
                    print(error.description)
                }
                if let guests = snapshot.children.allObjects as? [DataSnapshot] {

                    for (index,guest) in guests.enumerated() {
                        if let guestObject = guest.value as? String {
                            if guestObject == guestName {
                                self.guestList.remove(at: index)
                                self.refGuests.setValue(self.guestList)
                                DispatchQueue.main.async {
                                    self.guestsOnTableTableView.reloadData()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

enter image description here

Here is the shot from firebase.

1 Answer 1

0

It is not fully clear what you are trying to achieve.

Generally speaking you can remove elemets from arrays in firestore using the FieldValue.arrayRemove. https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/FieldValue

See example How to delete object from array in firestore

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

Comments

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.