Learn Courses My Dashboard

Showing Auth uid once it has been created (swiftui, firebase)

I am trying firebase Anonymous Sign in,
I want to print the uid once it has been created but fail to do so.

I can see the uid has been created in Firebase panel, but the swiftui can’t get and show it
(When I kill app and restart, swiftui can show the uid)

Here is the code:

import SwiftUI
import Firebase
import FirebaseAuth

@main
struct MyAnonymousAndAppleSignInTest2App: App {

    init(){
        FirebaseApp.configure()
        Auth.auth().signInAnonymously()
    }
     
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
import SwiftUI
import Firebase
import FirebaseAuth

struct ContentView: View {
    
    var body: some View {
        VStack{
            Text(Auth.auth().currentUser?.uid ?? "no uid returned")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I can only do this - Click a button to show uid:

import Foundation
import FirebaseAuth

class MyFirebaseService: ObservableObject{
    var currentID : String?
    var loggedIn = false
    
    func CheckIfSignedin(){
        currentID = Auth.auth().currentUser?.uid
        if currentID == nil{
            loggedIn = false
        } else {
            loggedIn = true
        }
    }
}
import SwiftUI
import Firebase
import FirebaseAuth

struct ContentView: View {
    @EnvironmentObject var myFirebaseService : MyFirebaseService
    @State var canShowUid = false
    
    var body: some View {
        VStack{
            if canShowUid == true {
                Text(myFirebaseService.currentID!)
            }

            Button {
                myFirebaseService.CheckIfSignedin()
                if myFirebaseService.loggedIn == true {
                    canShowUid = true
                } else {
                    canShowUid = false
                }
            } label: {
                Text("check uid update")
            }
            
        }
        .onAppear(perform: myFirebaseService.CheckIfSignedin)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}