I have tried to figure this out using tutorials and videos and can’t get it to work. My Firebase Realtime database has a table called “users”. In the users table are two fields – UserId and firstName.
I want to retrieve the firstName field value of the record where UserId = uid of currently logged in user. Here is my code:
//monitoring authchanges
onAuthStateChanged(auth, async (user) => {
if (user) {
const uid = user.uid;
const firstname = await getFirstnameOfLoggedInUser();
if (firstname) {
welcomeTxt.textContent = "Welcome back, " + firstname + "!";
} else {
// Handle case where firstname retrieval fails (optional)
}
} else {
console.log("user is logged out");
welcomeTxt.textContent = "Welcome! Please sign in or create an account.";
}
});
//get FirstName of person logged in
async function getFirstnameOfLoggedInUser() {
const user = auth.currentUser;
console.log(user);
if (user) {
const uid = user.uid;
console.log(uid);
const userRef = ref(database, "users/" + uid);
console.log(userRef);
get(userRef, (snapshot) => {
const userdata = snapshot.val().firstName;
console.log(userdata);
});
}
}
This code logs the current uid correctly but does not retrieve the correct record in the users table even though I see that the UserId and uid match. Please help!