Tuesday, 29 October 2019

Duplicates child node when setting a value Firebase

I've been trying to fix this for the last few days but keep ending up with the same result. When a user clicks to add a friend, it adds the friend's id as a node under "friends" (as expected); however, when I go to try and update or set a value for that id, it adds the id again with the value instead of just adding the value to the existing child. How do I make this so that it adds it without adding a whole other child?

enter image description here

Here's the code that adds the friend:

 func saveFriend(selectedFriend: FUser) {

    if friendId.contains(selectedFriend.objectId as String) {

        return
    }

    //get current friends
    var currentFriends = FUser.currentUser()!.friends

    currentFriends.append(selectedFriend.objectId)

    let newDate = dateFormatter().string(from: Date())
    let secondsDate: Int = Int(Date().timeIntervalSince1970)


    updateUser(withValues: [kFRIEND : currentFriends, kUPDATEDAT : newDate, kSECONDSDATEUPDATED : secondsDate]) { (success) in

        self.loadFriends()
        NotificationCenter.default.post(name: .addedFriend, object: nil)

    }


}

And this is the code to add the value (with the updateChildValues commented out that I also tried and had the same result):

func increaseFriendshipValue(increase: Int) {
    let friend = withUsers.first!.objectId
    let friendValueRef = firebase.child(kUSER).child(FUser.currentId()).child(kFRIEND).child(friend)

   // friendValueRef.updateChildValues([friend: +increase])

    friendValueRef.setValue(increase)


}

Edit: This is what I currently have in my Friends view where I load the friends from how they were added to an array (without the value):

  @objc func loadFriends() {
    cleanup()

    let friendIds = FUser.currentUser()!.friends

    if friendIds.count > 0 {

        for friendId in friendIds {

            firebase.child(kUSER).queryOrdered(byChild: kOBJECTID).queryEqual(toValue: friendId).observeSingleEvent(of: .value) { (snapshot) in

                if snapshot.exists() {
                    let userDictionary = ((snapshot.value as! NSDictionary).allValues as Array).first

                    let fuser = FUser.init(_dictionary: userDictionary as! NSDictionary)

                    self.friends.append(fuser)
                    self.friendId.append(fuser.objectId)
                    self.friends.sort(by: {$0.username < $1.username})
                }
                self.tableView.reloadData()

            }

        }

    } else {
        ProgressHUD.showError("You currently have no friends saved. Please unlock some")
    }

}


from Duplicates child node when setting a value Firebase

No comments:

Post a Comment