0

I am trying to find a way to connect my snapshot listener to specific variables, so that the rating average which is shown to the user is updated after each rating is submitted. Right now, I'm able to write new averages with the most recent submission taken into account to by Firestore Database. I can also see that my listener works by printing to the console, and it pulls the value that was just written each time. I'm trying to take what is written to the console and assign it to my variables at the top of the view structure so that each new submission is submitted on top of the previous submission averages.

struct NewRatingView: View {
    var schools = ["North Avenue", "West Village", "Brittain"]
    @State private var selectedSchool = "West Village"
    @State private var userCurrentRating: CGFloat = 0.0
    @State private var userUsualRating: CGFloat = 0.0
    @State private var isUserRatingCurrent = true
    @State private var averageCurrentRating: CGFloat = 2
    @State private var isUserRatingUsual = true
    @State private var averageUsualRating: CGFloat = 2
    @State private var totalRatingsCurrent = 1
    @State private var totalRatingsUsual = 1
// body view code

private func storeRatingInformation() {
        //        guard let uid = Auth.auth().currentUser?.uid else {return}
        let id = selectedSchool
        let ratingData = ["location": selectedSchool, "currentRating": averageCurrentRating, "usualRating": averageUsualRating, "totalCurrentRatings": totalRatingsCurrent, "totalUsualRatings": totalRatingsUsual] as [String : Any]
        let db = Firestore.firestore()
        db.collection("RatingInformation").document(id)
            .setData(ratingData) { error in
                if let error = error {
                    print(error)
                    return
                }
            }
    }
    
    private func snapshotListener() {
        let id = selectedSchool
        let db = Firestore.firestore()
        db.collection("RatingInformation").document(id)
            .addSnapshotListener { documentSnapshot, error in
                guard let document = documentSnapshot else {
                    print("Error fetching document: \(error!)")
                    return
                }
                if let currentRating = document.get("currentRating") as? CGFloat {
                    averageCurrentRating = currentRating
                    print("Testing:")
                    print(averageCurrentRating)
                    print(document.data())
                }
            }
    }
trndjc
  • 11,654
  • 3
  • 38
  • 51
FrancescaD
  • 11
  • 1
  • Show the entire `NewRatingView` structure, including the body code. – trndjc Oct 06 '22 at 19:59
  • Your question is about SwiftUI, not Firestore. Your Firestore code is fine. You're looking for something like this: https://stackoverflow.com/questions/70917713/swiftui-view-does-not-update-when-state-variable-changes – trndjc Oct 06 '22 at 20:01

0 Answers0