Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

537
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda