Unable to get uid from Firestore, unless user force closes the app and repopens

42 Views Asked by At

I am new to SwiftUI and I am currently practicing with Firebase Firestore. The problem that I am experiencing is when the user signs in, the code is unable to fetch the data (their first, last name, email and points) from the Firestore database, unless the user force closes the app and reopens it. Below is the code I have.

UserDataFetch.swift

import Foundation
import FirebaseAuth
import FirebaseFirestore

struct User {
    let uid, firstName, lastName, email: String
    let points: Int
}

class UserDataFetch: ObservableObject {
    
    @Published var uname: User?
    
    init() {
        
        fetchCurrentUser()
        
    }
    private func fetchCurrentUser() {
        
        
        guard let usID = Auth.auth().currentUser?.uid else {
            return
        }
        
            
        Firestore.firestore().collection("users").document(usID).addSnapshotListener { snapshot, error in
            if let error = error {
                print("Failed to fetch", error)
                return
            }
            
            guard let data = snapshot?.data() else {
                
                return
                
            }
            let uid = data["uid"] as? String ?? ""
            let firstName = data["firstName"] as? String ?? ""
            let lastName = data["lastName"] as? String ?? ""
            let points = data["points"] as? Int ?? 0
            let email = data["email"] as? String ?? ""
            
            self.uname = User(uid: uid, firstName: firstName, lastName: lastName, email: email, points: points)
            
        }
    }
}

Below is also the code from my login function. I am using @AppStorage("uid") var userID = "" to store and check if the user is logged in.

    func loginUser() {
    
        Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
            
            if let error = error {
                print(error)
                return
            }
            
            if let authResult = authResult {
                print(authResult.user.uid)
                userID = authResult.user.uid

            }
        }
    }

As I am still new I tried looking into the documentation of Firebase, I watched videos on YouTube, but I am still unable to come to a resolution. Any help would be greatly appreciated. Thank you!

1

There are 1 best solutions below

0
Tony Chronic On

I was able to fix the issue by running a '.onAppear' in the main ContentView file and simply getting the current userid, using a snapshot listener for the document(currentUserId) and then assigning the data to @State variables that I have declared. Now when the user signs in it automatically updates the information and also if there is any realtime updates, it automatically updates the view of the user.