1

I am currently trying to return the username from the firebase database in react native. The console.log works inside the function but doesn't log anything outside of the function. I don't know where I am going wrong. Here is my code.

  componentWillMount() {
    firebase.database().ref('/users/' + this.userId + '/username').once('value').then(function(snapshot) {
    this.username = snapshot.val();
    console.log(this.username)
    });
    console.log(this.username)
    this.setState({
      username: this.username
    })
  }  
Patty
  • 83
  • 6
  • 1
    This is expected behavior: the code *inside* the callback runs (potentially much) later than the code after it. See my explanation here: http://stackoverflow.com/questions/35419303/firebase-use-query-result-outside-function/35419533#35419533 – Frank van Puffelen Mar 06 '17 at 04:36

2 Answers2

0

This is because of asynchronous nature of JavaScript. You should do setState inside the callback.

firebase.database().ref('/users/' + this.userId + '/username').once('value').then(snapshot => {
    this.username = snapshot.val();
    console.log(this.username);
    this.setState({
      username: this.username
    })
});
vinayr
  • 11,026
  • 3
  • 46
  • 42
0

For some reason, changing the syntax to es6's arrow function made the code work along with adding this.setState inside the function

componentWillMount() {
    firebase.database().ref('/users/' + this.userId + '/username').once('value').then((snapshot) => {
    this.username = snapshot.val();
    console.log(this.username)
    this.setState({
      username: this.username
    })
  })
  }
Patty
  • 83
  • 6