Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing method vars from inside arrow function

In my vuetify/vue.js appliction, i'm trying to read a firestore collection I've stored to calculate an average rating from all ratings stored there:

function updateRating() {
  let firestoreQuery = firebase
      .firestore()
      .collection('ratings')
      .where('qrCodeId', '==', this.qrCode.id);

  let ratingsSum = 0;
  let ratingsAmountCounter = 0;

  firestoreQuery.get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      ratingsSum += doc.rating;
      ratingsAmountCounter++;
    });
  });
}

However, I can't access the ratingsSum and ratingsAmountCounter variables from inside my forEach arrow function. I've already tried using this or the var _this = this workaround, but both don't seem to work and eslint still reports:

'ratingsSum' is assigned a value but never used (no-unused-vars)

What am I doing wrong?

like image 416
Bas von Bassadin Avatar asked May 10 '26 21:05

Bas von Bassadin


1 Answers

As the comments suggest, the problem here is that you have no code that actually reads ratingsSum and ratingsAmountCounter. The error message is telling you that ESLint has triggered on the rule called "no-unused-vars" to tell you about this. Variables that are never read are probably a bug, or at least unnecessary code.

What you should probably do is return a promise to the caller so that they can get a hold of the values, whenever the asynchronous get() is complete and the values are computed. For example:

function updateRating() {
  let firestoreQuery = firebase
      .firestore()
      .collection('ratings')
      .where('qrCodeId', '==', this.qrCode.id);

  let ratingsSum = 0;
  let ratingsAmountCounter = 0;

  return firestoreQuery.get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      ratingsSum += doc.rating;
      ratingsAmountCounter++;
    });
    return { ratingsSum, ratingsAmountCounter }
  });
}

The caller of this function now receives a promise that resolves when the values are known, and they can be fetched out of the resolved object:

updateRating().then(result => {
  const { ratingsSum, ratingsAmountCounter } = result;
  // Now you can use ratingsSum and ratingsAmountCounter...
})
like image 90
Doug Stevenson Avatar answered May 13 '26 12:05

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!