0

I'm currently working on retrieving a child from Firebase with this code:

function fetchUserdetails() {
  firebase.database().ref().child('login/').orderByChild('username').equalTo('ivanaldwin').on("value", function(snapshot) {
    document.getElementById('fullname').innerHTML = snapshot.val().username;
    console.log(snapshot.val()); //debug in console
    snapshot.forEach(function(data) {
        console.log(data.key);
        alert('yep im working dood');
    });
});
}

window.onload = fetchUserdetails();

But the code, if i use snapshot.val().username; will render undefined in the output. but if i use snapshot.val() only, the output will be [Object object]. Here's my firebase layout:se

4
  • What do you get when you console.log(snapshot.val());? Commented Jan 27, 2019 at 15:22
  • also undefined. Commented Jan 27, 2019 at 15:22
  • How about console.log(typeof snapshot.val());? Commented Jan 27, 2019 at 15:23
  • now [object Object] and object Commented Jan 27, 2019 at 15:24

2 Answers 2

2

To retrieve the username try the following:

snapshot.forEach(function(data) {
    let userName = data.val().username;
    console.log(data.key);
    alert('yep Im working dude');
});

Your snapshot is at node login, therefore after you loop using forEach you then can access the child attributes.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked! Can't accept as answer yet though. Didn't know that the child attributes were sort of 'locked' at first.
0

You need to use array index

document.getElementById('fullname').innerHTML = snapshot.val()[0].username;

But I think you would need the element 0 for that one, which you don't have. Maybe try

document.getElementById('fullname').innerHTML = snapshot.val().child('1').username

2 Comments

Ended up spitting the error Cannot read property 'username' of undefined
the number 1 is a poor name for a node, as you can't reference it as an object child in your code. Either start from 0 so you would get an array where you can use my first line of code, or use names that are letters, where you can reference like snapshot.val().myNode.username

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.