Display user's data in an html tag after reading them from firebase for webapps

Viewed 46

This is the structure of my database, every user is in a child with value as that of their user-id

Database structure image

This is the code i am using

var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).child("userName").once('value').then(function(snapshot) {
  var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
  $("#name-tag").append(username);
});

I want the userName value and have to display it

2 Answers

First change the way you authenticate the user then create a proper reference to the database.

firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            // User is signed in.
            var userDBRef = firebase.database().ref().child("User Database").child(user.uid);
            userDBRef.on("value", function(userDB){
                $("#para-id").append(userDB.child("userName").val());
            });
        } else {
            // No user is signed in.
            console.log("no user!!!");
        }
        });

Try this code :

var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + 
userId).child("userName").once('value').then(function(snapshot) {
  var username = snapshot.val() ? snapshot.val().username) : 'Anonymous';
  $("#name-tag").append(username);
});

If snapshot.val() return null then usename will be 'Anonymus'

Related