1

I am new to Firebase, and I am trying to figure out how to retrieve data from my Firebase database. I was able to add to it successfully based on a user's unique id (uid), but now getting data from it seems to be incredibly difficult. I want to grab the first name from the current user ('user' in the following code), but this JavaScript doesn't seem to be working:

var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
    this.first_name = snapshot.val().first_name;
});

As soon as I make the call to this.first_name, it gives me the following error:

FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot set property 'first_name' of null.

In case it helps, my database is structured like this:

{
  users: {
    "uid1": {
      first_name: "John"
    },
    "uid2": {
      first_name: "Sue"
    }
  }
}
1
  • Your assigning a value to this.first_name. What are you expecting this to be? Since you're in the middle of a callback chain, the this context may be a variety of things (including null). Commented Jun 9, 2016 at 6:02

2 Answers 2

3

Use var first_name instead of this.first_name. It should work.

var uid = user.uid
firebase.database().ref('users/' + uid).on('value', function(snapshot) {
    var first_name = snapshot.val().first_name;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, that worked! However, I was using this.first_name before because I want to display that information in my HTML. Is there a way that I can do this?
OK, I figured it out. I just set the innerHTML to first_name.
3

The answer above is correct. but, i guess it's more readable if you use child in the query. Both should work.

firebase.database().ref('users').child(uid).on('value', function(snapshot) {
    var first_name = snapshot.val().first_name;
});

Comments

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.