Home > Software design >  Why is the data from firebase Firestore not coming into my view | Swift UI
Why is the data from firebase Firestore not coming into my view | Swift UI

Time:03-01

So I have tried for a couple of hours now and it is just not working. I have my firebase Firestore setup and have a collection called leaderboard, which is supposed to store users with their score. However, when I fetch this data and display it, my screen is blank.

Firebase enter image description here

LeaderBoardModel


import Foundation
import Firebase

class LeaderBoardModel: ObservableObject{
    
    @Published var users = [LeaderBoardItem]()
    
    func getData(){
        
        let db = Firestore.firestore()
        
        db.collection("leaderboard").getDocuments { snapshot, error in
            
            if error == nil{
                if let snapshot = snapshot{
                    
                    DispatchQueue.main.async {
                        self.users = snapshot.documents.map { d in
                            
                            return LeaderBoardItem(id: d.documentID, score: d["score"] as? String ?? "", name: d["name"] as? String ?? "", email: d["email"] as? String ?? "")
                        }
                    }
                  
                }
            }
            else{
                    
            }
        }
    }
}

LeaderBoardView

import SwiftUI

struct LeaderBoardView: View {
    
    @ObservedObject var leaderBoardModel = LeaderBoardModel()
    
    var body: some View {
        List(leaderBoardModel.users) { item in
            Text(item.name)
        }
    }
}

LeaderBoardItem

import Foundation

struct LeaderBoardItem: Identifiable{
    var id: String
    var score: String
    var name: String
    var email: String
}

CodePudding user response:

try this approach, using .onAppear{...}:

struct LeaderBoardView: View {
    
    @StateObject var leaderBoardModel = LeaderBoardModel() // <-- here
    
    var body: some View {
        List(leaderBoardModel.users) { item in
            Text(item.name)
        }.onAppear {
            leaderBoardModel.getData()  // <-- here
        }
    }
}
  • Related