0

How can I get a data as a string?

getData() {
  firebase.database().ref('users/USER_UID/username').on('value', snap => snap.val())
}
  console.log(this.getData())

Why is it that when I do this, I get undefined? The .ref() is a direct connection to a key. I just want to get its value.

I don't want to do this:

getData() {
  firebase.database().ref('users/USER_UID/username').on('value', snap => console.log(snap.val()))
}
  console.log(this.getData())
AL.
  • 36,815
  • 10
  • 142
  • 281
ajmakhl
  • 33
  • 1
  • 6

1 Answers1

0

Try passing snap.val() to a callback function:

getData(cb) {
  firebase.database().ref('users/USER_UID/username').on('value', snap => cb(snap.val()))
}

Then instead of console.log(this.getData()) you can run this.getData((val) => console.log(val))

Pat Needham
  • 5,698
  • 7
  • 43
  • 63
  • I tried that. It just gives me undefined. Someone told me it has to do with it being asynchronous. But why cant I get that return when I console log getData()? – ajmakhl Mar 13 '17 at 02:50
  • [This answer](http://stackoverflow.com/a/1557759/772985) explains why `undefined` is being printed, because you weren't returning anything from the function. – Pat Needham Mar 13 '17 at 02:58
  • so if I have a component and I want the value of that Text to be from a reference from my database. Say its from 'usernameList/user/username' and this ref () has a value of 'jef' How do I set that? The idea behind is to use a reference of database rather than duplicating it in other nodes. I just want to use one node that is spread throughout all other nodes – ajmakhl Mar 13 '17 at 04:16