0

I am trying to get the userid of a logged in user in order the query the firestore database for their profile information.

However I am unable to get the userid and am shown a blank page on my application. I think that this is because it is querying the database with a null userid before my getUserId() function returns a valid userID.

Does anyone know how i can fix this logic?

async function getUserId() {
  getAuth().onAuthStateChanged((user) => {
    if (user) {
      const uid = user.uid;
      console.log("1st uid:" + uid);
      return uid;
    } else {
      console.log("sad didnt work.");
    }
  });
}

async function getProfile() {
  const uid = await getUserId();
  console.info("2nd uid: " + uid);

  const docRef = doc(db, "profiles", uid);

  console.log("got docref");
  const docSnap = await getDoc(docRef);
  console.log("get for docsnap");

  if (docSnap.exists()) {
    const data = docSnap.data();
    console.info("successfully got profile: " + data);
    return data;
  } else {
    console.warn("GET PROFILE ERROR: DOCSNAP DOES NOT EXIST.");
  }
}

console errors

Tried: Created an asynchronious method to fetch current userid, then query database with acquired userid What i think happened: queried the database with null userid before asynchronious method returns valid userid.

1 Answers1

0

rewrite getUserId to return a Promise

function getUserId() {
    return new Promise((resolve, reject) => {
        getAuth().onAuthStateChanged((user) => {
            if (user) {
                const uid = user.uid;
                console.log("1st uid:" + uid);
                resolve(uid);
                
            } else {
                console.log("sad didnt work.");
                reject();
            }
        });
    });
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87