Search code examples
typescriptgoogle-cloud-firestorevuejs3

How to pass value or variable outside of onAuthStateChanged?


I'm currently trying to get authenticated user's uid from google authentication for specific collection from "User" document. I'm using onAuthStateChanged is to prevent data went null after refreshing the webpage. The code is provided as below:

import { getDoc, doc } from 'firebase/firestore'
import { onAuthStateChanged } from 'firebase/auth'

let UserUid = ""

onAuthStateChanged(auth, (user) => {
    if (user != null) {
        UserUid = user.uid
    }
    else {
        console.log("User is null")
    }
})

const docSnap = await getDoc(doc(db, "User", UserUid))

interface DataUser {
    FullName: string;
    Email: string;
    ContactNo: string;
    CountryCode: string;
    ICNO: string;
    HomeAddress: string;
    image: string;
    userType: UserType;
}

export const DataUser:DataUser = {
    FullName: docSnap.data()!["Name"],
    Email: docSnap.data()!["Email"],
    ContactNo: docSnap.data()!["Contact"],
    CountryCode: docSnap.data()!["CountryCode"],
    ICNO: docSnap.data()!["ICNO"],
    HomeAddress: docSnap.data()!["HomeAddress"],
    image: docSnap.data()!["Image"],
    userType: 0,
}

The error had occurred where UserUid in the last line shows that it was an empty string. It seems like the value did not pass to UserUid from onAuthStateChanged.

Is there anyways I can pass the value to UserUid?

I had tried using this.UserUid but it shows this was undefined.


Solution

  • When the page initially loads there is no current user yet, as Firebase needs to check with the server whether the credentials are still valid, and that takes time.

    There is no way to make the main code on your page wait until that call has been completed. So instead, your code will need to handle this situation, for example by rendering a "loading..." message. Then when the user credentials have loaded, you can execute the code that needs the UID - so by calling it from onAuthStateChanged.