Home > Software design >  Uncaught TypeError: Cannot read properties of null (reading 'email')
Uncaught TypeError: Cannot read properties of null (reading 'email')

Time:11-22

I am trying to get the email of the currently logged in user which I will then use to get the name data field from the document corresponding to this user. However, I keep getting this error. Any idea on how to fix this issue would be highly appreciated.

Additionally, whenever I make any change in regard to the email issue, I get the following error: Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_4__.db.collection is not a function

And when I refresh the page it returns back to the error in the title.

const auth = getAuth();
const user = auth.currentUser;
const userEmail = user.email;
let clubName;

db.collection("users").where("email", "==", userEmail).get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    console.log(doc.id, " => ", doc.data());
    let data = doc.data();
    clubName = data.name;
  });
}).catch(function(error) {
  console.log("Error getting documents: ", error);
});
console.log("THE DATA YOU ARE LOOKING FOR: "   clubName);
const q = query(collection(db, "requests"), where("SendTo", "==", clubName));

NOTE: in the code above I am using 2 different firebase databases one called users which has the fields {email, name, password, job} and the other called requests which have the following fields {From, SendTo, type, content, header}

CodePudding user response:

auth.currentUser might be null because the auth object has not finished initializing.

Try using onAuthStateChanged assuming you are using firebase v9.

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
   // User is signed in

  } else {
    // User is signed out  

  }
});
  • Related