admin 管理员组

文章数量: 1086019

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

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;
}
Share Improve this question edited Feb 23, 2022 at 22:16 Frank van Puffelen 600k85 gold badges890 silver badges860 bronze badges Recognized by Google Cloud Collective asked Feb 23, 2022 at 21:50 Uri GrossUri Gross 5241 gold badge8 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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 pletely clear to me (a beginner as a developer).

本文标签: javascriptAngular returning a value from onValue() in firebase realtime databaseStack Overflow