Skip to content
Advertisement

How to return the document data got from firestore using .get() to another function in JS

I have a function that needs some data from firestore and I want to make another function that will get the data and return it to the function calling it

The code that I’m trying:

function getData(){
    var dataNeeded;
    let finalData = await db.collection("Trial").doc("trialDoc").get().then(doc => {
        dataNeeded = doc.data();
        console.log(dataNeeded);
        return dataNeeded;
    });
    return finalData;
}

function logic() {
dataRecieved = getData();

Here my logic function needs to use data that is received from the getData function

Any suggestions on how to get the data in this way?

Advertisement

Answer

You need to use a promise

function getData() {
  return Firebase.firestore().collection("Trial").doc("trialDoc").get()
}

async function login() {
  const dataRecieved = await getData();
  // you can data using dataRecieved.data()
  // your logic here
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement