Ben Cavenagh
Ben Cavenagh

Reputation: 748

Firebase .childAdded observer duplicating children

I am trying to have my program add every instance of a child to an array but whenever I delete a child then add another it duplicates that added child twice and if I do it again it will duplicate 3 times and so on depending on how many times I delete and add. The adding and deleting is mainly handled in the function below and I can't figure out why it is duplicating them.

func fetchContacts(completion: @escaping () -> ()){
    contacts = [Contact]()
    let userRef = ref.child("users").child(user).child("contacts")

    userRef.observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject]{
            print(snapshot)
            let contact = Contact()
            contact.setValuesForKeys(dictionary)
            self.contacts.append(contact)
        }
        self.contactsTable.reloadData()
        completion()
    }, withCancel: nil)

    userRef.observe(.childRemoved, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject]{
            let contact = Contact()
            contact.setValuesForKeys(dictionary)
            if let i = self.contacts.index(where: { $0.name == contact.name }) {
                self.contacts.remove(at: i)
            }
        }
        self.contactsTable.reloadData()
        completion()
    }, withCancel: nil)
}

Here is where the deleting is handled and how the functions are called in the viewDidLoad:

override func viewDidLoad() {
    contactsTable.delegate = self
    contactsTable.dataSource = self
    contactsTable.rowHeight = 65
    super.viewDidLoad()
    fetchContacts(){
        self.contactsTable.reloadData()
    }
}

func handleDelete(phone: String, completion: @escaping () -> ()){
    let userRef = ref.child("users").child(user).child("contacts")
    userRef.child(phone).removeValue { (error, ref) in
        if error != nil {
            print("Error: \(error)")
        }
        completion()
    }
}

Upvotes: 1

Views: 392

Answers (1)

Bradley Mackey
Bradley Mackey

Reputation: 7668

This may be to do with you not calling reloadData() on the main thread.

Instead of just:

self.contactsTable.reloadData()

try:

DispatchQueue.main.async {
    self.contactsTable.reloadData()
}

Upvotes: 2

Related Questions