I'm currently building an app and i faced some issues. I use Firebase to store the user data and then i display it in some of the views, i managed to create the function to retrieve data with completion, so the async issue is solved, but now when i need to display some of the data it displays nil, because the view is loaded sooner than the firebase loads. My function to load data from firebase:
func getUserFromUID(completion: @escaping (UserData)->()){
ref.child("users").child(uid).observe(.value) { (snapshot) in
DispatchQueue.main.async {
guard let dictionary = snapshot.value as? [String:AnyObject] else { return}
var user = UserData()
if let email = dictionary["email"]{ user.email = email as? String }
if let name = dictionary["name"]{ user.name = name as? String }
user.firstname = (dictionary["firstname"] as! String)
user.lastname = (dictionary["lastname"] as! String)
user.type = (dictionary["type"] as! String)
user.uid = (dictionary["uid"] as! String)
user.profileImageUrl = (dictionary["profileImageUrl"] as! String)
user.id = snapshot.key
user.fcmToken2 = (dictionary["fcmToken"] as! String)
completion(user)
}
}
}
ChatsHomeView:
struct ChatsHomeView: View {
@ObservedObject var session : SessionStore
@State var user = UserData()
func getUserInfo(){
session.getUserFromUID { (fetcheduser) in
self.user = fetcheduser
print("THE USER:\(user)")
}
}
var body: some View {
VStack{
Text(user.name ?? "nil")
Button(action: {
session.signOut()
}){ Text("Logout").padding() }
}.onAppear{
getUserInfo()
}
}
}
The problem is, that once the user logins, it displays nil where the ChatsHomeView Text(user.name ?? "nil") field is. I need to restart the app for the field to update and show the Name. Is there a way to show the app launch screen until firebase fully loads, or maybe there is any other way? Thanks in advance, hope this is enough to understand the problem. <3