'How can I map and assign multiple documents to a published property using Firebase/SwiftUI?
My Database is structured like this:
Main Collections:
- Users
- Followers(who follows the current user)
The followers collection stores a list of ID's (each user's ID). Each of these document stores an "inbox" sub collection which stores a list of users ID's of people who they've added as friends, or people who have requested to be friends with them.
Each one of those ID's stores a "currentStatus" property which is set to "pending" if they haven't been added yet or "contact" if they have (this is how I make the query to fetch either contacts or requests). I then use the ID's to go into my user collection to fetch the associated users.
The problem I'm having is my function gets the data but because i'm appending it to the published array there's duplicate data (each user shows up twice on the screen). So I need to be assigning all the mapped documents to the property itself, which I dont know how to do....
"The problem is that you're appending the documents to the published property. This will lead to duplicating the entries.
Instead, just assign all of the mapped documents to the emergencyContactUsers property.
Check out Mapping Firestore Data in Swift - The Comprehensive Guide | Peter Friese for more details about this. I've also got a number of other posts about Firestore and SwiftUI on my blog that might be useful."
-Peter Friese said this and ive been stuck trying to do what he said.
@Published var userRequestInboxUsers = [User]()
@Published var emergencyContactUsers = [User]()
func fetchTheUsersRequests() {
guard let uid = shared.currentUser?.id else { return }
let query = COLLECTION_FOLLOWERS.document(uid).collection("inbox").whereField("currentStatus", isEqualTo: "isPending")
print("Query for the requests is about to start now...")
query.getDocuments { snapshot, error in
if let error = error {
print("There was an error querying the inbox requests: \(error.localizedDescription)")
} else {
for request in snapshot!.documents {
COLLECTION_USERS.document(request.documentID).getDocument { snapshot, error in
if let error = error {
print("There was an error fetching the user data: \(error)")
} else {
guard let userRequestInInbox = try? snapshot?.data(as: User.self) else { return }
self.userRequestInboxUsers.append(userRequestInInbox)
print("User request function has been ran...")
}
}
}
}
}
}
This function works perfectly besides the fact that it gives me duplicated results.
My func getContacts() essentially is ran the exact same way just the query is different.
A link to my original question will be here: SwiftIU/Firebase: How to update lists of users from Firebase in real time and have it reflect in the UI?
Any help would be greatly appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
