Hello!
I've been working on a web project where a user is able to sign up and log in. I wanted to add a profile too, where some info they've provided could be diplayed on the page 'Profile'.
I've already used firebase auth (with email & password) and rt database to store extra info like 'Name', 'Bio', etc.
What I seem to not understand is how to retrieve the info that's stored on the database and display it on a < p > tag on the profile page.
I've already tried solutions from other questions asked in here but none seemed to work for me.
This is how my database is looking:
users:
|
+-uid1
|
+-Name
|
+-Gender..
|
+-uid2
|
+-Name
|
+-Gender..
Here is some code for the profile page:
What i was trying to do here is get the current user that's logged in and display the name on the profile - on a < p > tag that has an id=username.
//getting reference to the apps
const auth = firebase.auth();
const database = firebase.database();
//also creating table 'users' on database
const rootRef = database.ref('users');
// ------------------------------------//
//Check if signed in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
database.ref('/users/'+ userId).on('value')
.then(function(snapshot) {
var snapVal = snapshot.val();
displayName.innerHTML = snapVal.Name
var name = diplayName
document.getElementById("username").innerHTML = "Welcome: " + name + "!";
})
} else {
// No user is signed in.
window.location = "login.html"
}
});
When I tested the code I got this error on the console:
Error: Query.on failed: Was called with 1 argument. Expects at least 2.
Also, I don't really know if I am using this function correctly.
Should I replace 'userId' with something else?
database.ref('/users/'+ userId ).on('value')
Thank you for reading this and have a nice day!
You're not setting userId
to anything yet. When your onAuthStateChanged
callback is called, and user
has a value, you know that a user is signed in. At that point you can get that user's UID by doing user.uid
.
So something like:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
database.ref('/users/'+ user.uid).once('value')
.then(function(snaphot) {
document.getElementById("username").innerText = "Welcome: " + snapshot.val().Name;
})
} else {
window.location = "login.html"
}
});
The Name
in snapshot.val().Name
needs to match whatever property from the user node in the database you want to show
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.