Home > Software design >  How to get firebase data to return from a function?
How to get firebase data to return from a function?

Time:04-03

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.

CodePudding user response:

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?
}
  • Related