Only append NEW project to collectionview (Firebase/Firestore)

Viewed 63

On an app Im working on, users are able to upload projects by selecting an "upload project" button. Selecting this button triggers a segue to a screen where the user can now input their information for the project. Once the information is filled in and users select "upload", the screen dismisses itself, returning the user to their profile. The problem is that when a user returns to the profile screen, the project they just uploaded does not show in the collection view. it only shows the projects that were downloaded when the user first viewed their profile.

To try and fix this, I added a snapshot listener. The problem with this is: It loads the new project in, but in return, it loads every project twice. How can I set it up to where only the new project is appended, instead of every project being added again?

func setUserProjects(){
    let uid = Auth.auth().currentUser?.uid
    let db = Firestore.firestore()
    let docRef = db.collection("projects")
    
    docRef.whereField("uid", isEqualTo: uid!).getDocuments { (snapshot, err) in
        if let err = err {
            print("Error:\(err)")
        } else {
            for document in snapshot!.documents {
                var dictionary = document.data()
                let project = Project(dictionary: dictionary as [String: AnyObject])
                project.id = document.documentID
                self.userProjects.append(project)
                self.userProjects.uniqued()
            }
        }
        self.projectsCollectionView.reloadData()
    }
    
    
    docRef.whereField("uid", isEqualTo: uid!).addSnapshotListener { snapshot, err in
        if let err = err {
            print("Error:\(err)")
        } else {
            for document in snapshot!.documents {
                var dictionary = document.data()
                let project = Project(dictionary: dictionary as [String: AnyObject])
                project.id = document.documentID

                ///only append the project if it's not already added
                if !self.userProjects.contains(project) {
                    self.userProjects.append(project)
                }
            }
        }
    }
    
}
0 Answers
Related