1

I am pulling data from Firebase. I want to extract values and save them in the array. After that I will use that array values as strings in my application. The problem is when I push values from DB to array, it adds undefined at the end of the array. And when I want to see the value of array (carUserDetails[0]) it returns undefined, but should return a string "BMW"

var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);

var carUserDetails = [];

refModels.once('value').then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {
        var usersValue = childSnapshot.val(); //get the values of the object
        carUserDetails.push(
            usersValue.carMake, 
            usersValue.carYear, 
            usersValue.carModel, 
            usersValue.carTrim
        );
    });
});

console.log(carUserDetails);

enter image description here

console.log(carUserDetails[0]) // returns undefined too

So what could be the problem

AlexFF1
  • 1,233
  • 4
  • 22
  • 43
  • 1
    Check if your loop is executing 2 times. And then in second iteration usersValue.carMake can be undefined – Lalit Jul 31 '17 at 12:39
  • 1
    What do you get if you print `snapshot`? – smartmouse Jul 31 '17 at 12:44
  • add a console.log just after push to print uservalue and see what it prints probably your loop executing twice. and you are getting carUserDetails[0 undefined because of Asynchronous code execution – Tripurari Shankar Jul 31 '17 at 12:45
  • After I console log after the push it print out twice. So looks like it executes twice. and how to improve this? – AlexFF1 Jul 31 '17 at 12:54

2 Answers2

1

So yes it an asynchronous call issue. See the fix

var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);

var carUserDetails = [];

refModels.once('value').then(function (snapshot) {
  snapshot.forEach(function (childSnapshot) {
    var usersValue = childSnapshot.val(); //get the values of the object
    carUserDetails.push(
        usersValue.carMake, 
        usersValue.carYear, 
        usersValue.carModel, 
        usersValue.carTrim
      );
     });

     $scope.getValueFromArray(); //call function here

    });



$scope.getValueFromArray = function(){

   console.log(carUserDetails[0]); returns "BMW"
 }
AlexFF1
  • 1,233
  • 4
  • 22
  • 43
1

I think it's because you are too early calling console.log remember reading firebase value is asynchronous. You should put your console, inside function (snapshot) and after snapshot.forEach

refModels.once('value').then(function (snapshot) {
  snapshot.forEach(function (childSnapshot) {
    ....
  });
  console.log(carUserDetails);
});
Faruk
  • 5,438
  • 3
  • 30
  • 46