0

How should I get 'full_name' from the object that was created from firebase database snapshot.

const profile_grabber = firebase.database().ref('PublicUserData').orderByChild('full_name');
var returnArr = [];

profile_grabber.once('value', function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
        var item = childSnapshot.val();
        item.key = childSnapshot.key;
        returnArr.push(item);
      });
}).catch(function(error){
   console.log(error.code);
   console.log(error.message);
});

  console.log(returnArr);
  console.log(returnArr[0].full_name);

Console.log() results

//console.log(returnArr);

[] 0: { birth_day: "1996-05-23", full_address: "address 0", full_name: " Udayanga", … }

1: { birth_day: "1997-03-13", full_address: "address 4 ", full_name: "Akila Athauda", … }

2: { birth_day: "1996-10-18", full_address: "address 5 ", full_name: "Chamindu Milan", … }

3: { birth_day: "1996-03-03", full_address: "address 1 ", full_name: "Dilshan Rajapaksha", … }

4: { birth_day: "1997-01-08", full_address: "address 2", full_name: "Gimhana Jayasekara", … }

length: 5 proto: Array(0)

//console.log(returnArr[0].full_name);

Uncaught TypeError: Cannot read property 'full_name' of undefined

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Data is loaded from Firebase asynchronously. While the data is being loaded, your main code continues, and that is when your `console.log(returnArr[0].full_name);` runs and logs the error. Then when the data is available, your callback is called and set the variable. Chrome is doing you a disservice here, and updates the output from `console.log(returnArr);` dynamically once the callback run. – Frank van Puffelen Sep 14 '19 at 21:28
  • All this means is that any code that requires the data from the database, must be inside the callback, or be called from there. For examples of both, see my answer here: https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890 and some of the others here: https://stackoverflow.com/search?tab=votes&q=%5bfirebase-realtime-database%5d%5bjavascript%5d%20asynchronous%20user%3a209103 – Frank van Puffelen Sep 14 '19 at 21:29
  • @FrankvanPuffelen you were right. Thank you so much. All I needed to do was to put rest of the code inside the firebase database snapshot callback function. – Gimhana Jayasekara Sep 15 '19 at 11:37

1 Answers1

0

Try this:

var item = childSnapshot.val();
for(i in item){
console.log(item[i]['full_name']);
}
MarkWalczak
  • 1,532
  • 3
  • 16
  • 24