An async function UserTest calls and awaits an async function GetUser but the value returned by GetUser is undefined

32 views Asked by At

Code for GetUser.tsx is:

import { auth } from "../lib/firebase";

var currentUserID: string | undefined;

async function GetUser() {
    auth.onAuthStateChanged(async (user) => {
        const userValue = user;
        currentUserID = user?.uid;
        console.log("in get user and user id = " + currentUserID);
        console.log("in get user and user value = " + userValue);
    });

    return currentUserID;
}
export default GetUser;

Code for UserTest.tsx is:

import GetUser from "./GetUser";

async function UserTest() {
    const userUID = await GetUser(); 
    console.log("UserTest after await and userUID = " + userUID);

    return <div>To Do...</div>;
}
UserTest();
export default UserTest;

So UserTest calls GetUser and expects a Promise but even after the await in GetUser() to resolve the Promise into a value the value of userUID is still undefined. The console log from GetUser has values for currentUserID and userValue. But the console log from UserTest shows userUID as undefined even though its value is being assigned from an "await' expression.

0

There are 0 answers