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

Viewed 1616

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;
}
2 Answers

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

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).

Related