0

I am trying to get data from firebase Realtime database. I know how to get the data, I can log it, but it is not returning. It always return undefined if I use that function anywhere else in my code to set that data to a variable.


function getData(target) {
  const reference = ref(db, `${target}/`);
  onValue(reference, (snapshot) => {
    if (snapshot.exists()) {
      console.log(snapshot.val());
      return snapshot.val();
    }
  });
}

The console.log(snapshot.val()); works

I tried many solution, but couldn't get it to work the way I want it to be. Basically, I want to get data from firebase and make it function, so that I can use it in my other files, just by passing a database reference. Everything work except it doesn't not return that value.

Ejaj Ahmad
  • 80
  • 6
  • The `return` statement is returning values from the **callback** function, not really from the `getData` that you defined. – chris Apr 03 '22 at 03:39

1 Answers1

1

It sounds like you only want to read data once, which you can do with get() like this:

function getData(target) {
  const reference = ref(db, `${target}/`);
  return get(reference).then((snapshot) => {
    if (snapshot.exists()) {
      return snapshot.val();
    }
    // TODO: what do you want to return when the snapshot does *not* exist?
  });
}

Or with async/await

async function getData(target) {
  const reference = ref(db, `${target}/`);
  const snapshot = get(reference);
  if (snapshot.exists()) {
    return snapshot.val();
  }
  // TODO: what do you want to return when the snapshot does *not* exist?
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hey thank you for your above solution. the `get()` one worked. I just have a another simple question. Do you happen to know how can I sort that data by recent and older. I have tried this: ` db.ref(`${target}`) .orderByChild("uniqueID") .on("child_added", (snap) => { console.log(snap.val()); });` but its outdated I think – Ejaj Ahmad Apr 05 '22 at 08:36
  • I don't think anything significantly changed about ordering data in the API for many years now, but I don't immediately see what's wrong there. If it continues to not work, it might be worth opening a new question for that with its own [minimal repro](http://stackoverflow.com/help/mcve). – Frank van Puffelen Apr 05 '22 at 14:34