Ace
Ace

Reputation: 489

Firebase snapshot.val() returns [object Object]

Im trying to retrieve a user from firebase DB but when I print the snapshot.val() it shows [object Object]. How can I print the real data? Thanks!

  FriendlyChat.prototype.getRandomInterlocutor = async function(){
var numberOfUsers = await this.getNumberOfUsersRef();

var randomIndex = Math.floor(Math.random() * numberOfUsers);
if(randomIndex == 0){
  randomIndex = 1;
}

var ref = await firebase.database().ref('companies/' + this.company + '/users/');
ref.limitToFirst(randomIndex).once('value').then(snapshot =>
{
    var user = snapshot.val();
    console.log('getRandomInterlocutor = ' + user); 
    return user;
});
  }

FriendlyChat.prototype.onAuthStateChanged = function(user) {
  console.log('entro a onAuthStateChanged');
  this.interlocutor = this.getRandomInterlocutor();
  console.log(this.interlocutor);
}

Upvotes: 2

Views: 2827

Answers (1)

larv
larv

Reputation: 938

Just print console.log(user); and not a string with the obj in it. this reproduce it:

var obj = [{a: 1}, {a: 'lucas', b: 2}];
console.log('current obj', obj);

However as user is an array, you can just do this to get each objet as you want it. (ES6)

user.forEach((u, key) => {
    // u contains your user data object which is like u.uid and u.email or whatever keys you got.
    console.log(key, 'key here contains the strange "firebase array index key"');
    console.log(u);
});

Upvotes: 1

Related Questions