lucas romero
lucas romero

Reputation: 41

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'
}

Upvotes: 3

Views: 899

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317372

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();
    });
}

Upvotes: 2

szczocik
szczocik

Reputation: 1333

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();
    });
}

Upvotes: 1

Related Questions