Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

535
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!