Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

533
Vistas
Angular: returning a value from onValue() in firebase realtime database

I would like to return the "User" object.

Got error message:

Variable 'user' is used before being assigned.ts(2454)

I tried to use async / await but I can't assign await to "return user" at the end of the code or user= await snapshot.val() because it is located on onValue() scope.

getLoggedInUser(id: string): User {
  const db = getDatabase();
  var user: User;
  onValue(ref(db, '/users/' + id), (snapshot) => {
    user = snapshot.val();
    // ...
  }, {
    onlyOnce: true
  });
  return user;
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

When you call onValue you get the current value from that path in the database, and then also get all updates to that value. Since your callback may be called multiple times, there is no way to return a single value.

If you want to just get the value once and return it, you'll want to use get instead of onValue. Then you can also use async/await.

async getLoggedInUser(id: string): Promise<User> {
  const db = getDatabase();
  var user: User;
  const snapshot = await get(ref(db, '/users/' + id))
  user = snapshot.val();
  return user;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I am actually having a similar issue, although I try to fetch data with paging logic. We do have thousands of records and to render them nicely (10 - 25 per page) would be the best option anyhow.

const dbRef = query(ref(database, folder), orderByChild(field), startAt(start), limitToLast(limit))
return onValue(dbRef, (snapshot) => {
    const values = Object.values(snapshot.val());
    return {data: values, total: values.length, page: page}
    })

I can see the values inside the onValue, but it seems not to return the value at all. I'm not sure where to go here, the documentation on that is not completely clear to me (a beginner as a developer).

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda