2

Here's my problem:

getPlaceNames(){
var places = [];
var source =firebase.database().ref(`${this.props.countryProp}/${this.props.cityProp}`);
source.on('value', function(snapshot){
  for (var key in snapshot.val())
    places.push(key);
});
console.log(places);
return places;
}

So what's happening is that places still ends up as an empty array after the loop is done. What exactly is happening here and how do I fix it ?

1 Answers1

1

you are using async call. in your code, the function(snapshot) hasn't been called when console.log(places); is executed.

so callback can be used:

function getPlaceNames(callback){
    var source = firebase.database().ref(`${this.props.countryProp}/${this.props.cityProp}`);
    source.on('value', function(snapshot){
        var places = [];
        for (var key in snapshot.val()) {
            console.log(key);
            places.push(key);
        }
        callback(places);
    });
}

getPlaceNames(function(places){
    console.log(places);
});
shawn
  • 4,305
  • 1
  • 17
  • 25