Home > Software engineering >  Updating all current user's posts works, but after signing up with a new account, it updates a
Updating all current user's posts works, but after signing up with a new account, it updates a

Time:05-10

In my app, I have users choosing premade avatars. In Firebase, each user’s avatar has two properties. These are image and image-color. The images are project assets, and the colors are saved as integers that get switched and converted to colors. I save the user’s image in users/uid/image, and image color in users/uid/image-color. When I read a post and add each value to my Post model, the image and image color persist even if the user changes their image or color. I fixed this by making this query:

guard let user = UserService.currentUserProfile else { return }
            

let ref = Database.database().reference().child("posts").queryOrdered(byChild: "author/uid").queryEqual(toValue: user.uid)
ref.observeSingleEvent(of: .value) { snapshot in
    if snapshot.exists() {
        print(snapshot)
        for i in snapshot.children {
            guard let childSnapshot = i as? DataSnapshot else { return }
            let key = childSnapshot.key


            let postRef = Database.database().reference().child("posts").child(key)
            postRef.child("author").updateChildValues(["image": self.chosenAvatar, "image-color": self.chosenColor as Any])
        }
    }
}

This query works perfectly, but my problem is that when I sign the current user out, and sign up with a new account, I change the new user’s profile image and color, and it updates the other account’s posts that I was signed into before. A print statement will even show the current user’s uid is not the one in the post it updates. Here is my Firebase data structure for a post with relevant nodes :

"posts": {
    "[post_id]": {
      "author": {
        "image": "avatar-3",
        "image-color": 3,
        "uid": "[uid]",
        "username": "[username]"
      },

Please let me know if you know why this is happening, or if I need to include something else.

CodePudding user response:

It sounds like you're not updating your user variable, when signing a user in or out, which then leads to user.uid referring to the user who was signed in when the app started.

To fix this, you'll want to implement an auth state listener as shown in the first code snippet in the documentation on getting the current user.

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

By using a listener your callback will be called whenever the auth state changes (including when a new user signs in), so this is the perfect time to update your user variable.

  • Related