'How to return the snapshot.val() to be used later in the code

I am using the firebase realtime database web version 9, and I am trying to return the value of snapshot.val() as a variable to be used later in testing. when I console.log(snapshot.val()) it logs the correct result, and when I try to return it, it returns undefined.

Here is my code:

import { getDatabase, ref, child, get } from "firebase/database";

const dbRef = ref(getDatabase());
get(child(dbRef, `users/${userId}`)).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("No data available");
  }
}).catch((error) => {
  console.error(error);
});

How can I return the value of snapshot.val()?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source