Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snapshot.val() returns undefined, but it logs correctly. Node.js firebase

I dont know why, but when i return the object in snapshot.val() it doesn't return anything to my front, but when i console.log() it, it shows the object correctly. Here's how i'm returning it:

function Loggear({ email, password }) {
  db.ref("Usuarios")
    .orderByChild("email")
    .equalTo(email)
    .on("child_added", (snapshot) => {
      console.log(snapshot.val())
      return snapshot.val();
    });
}

How it shows my object on console.log():

{
  ciudad: 'Buenos Aires',
  codigoPostal: '1000',
  direccionCalle: 'la casa de tomas',
  direccionNumero: '1',
  documento: '1',
  email: '[email protected]',
  fechaNacimiento: '1111-01-01',
  nombreCompleto: 'firebase',
  password: 'contraseña',
  telefonoCelular: '1233'
}
like image 413
lucas romero Avatar asked Dec 21 '25 01:12

lucas romero


2 Answers

If you just want to fetch data a single time, use once() instead of on(), as shown in the documentation. on() sets up a persistent listener at some database location, and will invoke your callback function every time something changes at that location. That's not what you want. Instead use once(), which returns promise that resolves with the snapshot of data:

function Loggear({ email, password }) {
  return db.ref("Usuarios")
    .orderByChild("email")
    .equalTo(email)
    .once("value", (snapshot) => {
      console.log(snapshot.val())
      return snapshot.val();
    });
}
like image 141
Doug Stevenson Avatar answered Dec 23 '25 15:12

Doug Stevenson


I think this is happening because you are not returning any value from the Loggear function itself. The value from the on child added is only returned to the scope of Loggear. You will have to return it from the function itself, i.e.

function Loggear({ email, password }) {
  return db.ref("Usuarios")
    .orderByChild("email")
    .equalTo(email)
    .on("child_added", (snapshot) => {
      console.log(snapshot.val())
      return snapshot.val();
    });
}
like image 35
szczocik Avatar answered Dec 23 '25 14:12

szczocik