I am trying to create a feature where if a user likes a post, closes the app and reloads the app, the like button is still red and the user will not be able to like the post again unless they unlike it first.
A previous post recommended me to use an array, so thats exactly what I did. I've created an array that when a post is liked, the users UID goes to the array. Array is in "Posts/(postid)"
Now, what I can't figure out is how to see if a users UID is equal to a UID found in this array. My goal is if a users UID is already on the array, set the variable "isLiked" to true. If it's not, have "isLiked" be false (which is already done).
PostViewModel.swift
func addLike(id: String){
ref.collection("Posts").document(id).updateData(["likes": FieldValue.increment(Int64(1))]) { (err) in
if err != nil{
print(err!.localizedDescription)
return
}
self.ref.collection("Posts").document(id).updateData([
"likedBy": FieldValue.arrayUnion([self.uid])
])
}
}
func unLike(id: String){
ref.collection("Posts").document(id).updateData(["likes": FieldValue.increment(Int64(-1))]) { (err) in
if err != nil{
print(err!.localizedDescription)
return
}
self.ref.collection("Posts").document(id).updateData([
"likedBy": FieldValue.arrayRemove([self.uid])
])
}
}
PostRow.swift
@State private var isLiked = false
HStack {
Button(action: {if isLiked == false{
postData.addLike(id: post.id)
isLiked = true
} else{
postData.unLike(id: post.id)
isLiked = false
}}, label: {
Image(systemName: isLiked ? "heart.fill" : "heart")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 20)
.foregroundColor(isLiked ? .red : .gray)
})
}