Home > database >  How to export/read data from async function that's querying firebase
How to export/read data from async function that's querying firebase

Time:07-08

Learning how to use react by creating a project.

I am trying to filter the data by when it was added into the collection. Then I am trying to add all the totalCalories in a certain amount of time so i can display it in form using react.

However, I do not know how to get the values for totalCalories and also get the other fields like mealTime. I want to display all of them in my app.js However when i do i get undefined, or says promise pending.

Any help would be massively appreciated. Thanks

firebase.js

    export async function run() {
      const time = 48;
      const timediff = moment(new Date()).subtract(time, "hours")._d;
      await db
        .collection("/food/meals")
        .where("mealTime", ">=", timediff)
        .get()
        .then((qSnapshot) => {
          let totalCalories = 0;
          qSnapshot.forEach(function (doc) {
            totalCalories  = doc.data().calories;
            console.log(doc.id, " -> ", doc.data());
          });
          console.log(totalCalories);
          return totalCalories;
        })
        .catch(function (error) {
          console.log("Error getting documents: ", error);
        });
    }
    
    run(); //returns nothing 
    console.log(run()); //Promise {<pending>}
    
    console.log(run().totalCalories); //undefined

CodePudding user response:

Try this :

Instead of :

await db...

=>

return db...

run doesn't need to be an async function anymore

run().then(totalCalories => console.log('totalCalories :', totalCalories));

Now run return a promise, when this promise is resolved it return the totalCalories returned by your db query

Full code :

function run() {
    const time = 48;
    const timediff = moment(new Date()).subtract(time, "hours")._d;
    return db // this is returned by the function (as a promise)
      .collection("/food/meals")
      .where("mealTime", ">=", timediff)
      .get()
      .then((qSnapshot) => {
        let totalCalories = 0;
        qSnapshot.forEach(function (doc) {
          totalCalories  = doc.data().calories;
          console.log(doc.id, " -> ", doc.data());
        });
        console.log(totalCalories);
        return totalCalories; //this is returned by db query
      })
      .catch(function (error) {
        console.log("Error getting documents: ", error);
      });
  }

// if your code is an ES6 module
let result = await run(); 
console.log('Result :', result);

// else
run().then(result => console.log('Total : ', result));

// to export this as ES6 Module
export { run }
// or
export default run;

To return all the data calculated value totalCalories you can do :

return { ...doc.data(),  'totalCalories': totalCalories };
  • Related