Christoffer Endresen
Christoffer Endresen

Reputation: 39

Reach content of variable in another method

I'm trying to reach the content of matchData from a Vue method. I'm able to console.log(this.matchData), but not able to get its content.

When I console.log(this.matchData[0].matchScores[0]) under method readMatchPlayerScoreIds() I get:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'matchScores' of undefined"

export default {
  data() {
    return {
      matchData: [],
    };
  },
  methods: {
    readMatches() {
      db.collection("matches")
        .get()
        .then((queryMatchSnapshot) => {
          queryMatchSnapshot.forEach((doc) => {
            this.matchData = [];
            this.matchData.push({
              awayscore: doc.data().awayscore,
              homeScore: doc.data().homeScore, 
              matchScores: doc.data().matchscores,
            })
          });
          console.log(this.matchData[0].matchScores[0])
        });
      },

      readMatchPlayerScoreIds() {
          console.log(this.matchData[0].matchScores[0])
      }
  },
  mounted() {
    this.readMatches();
    this.readMatchPlayerScoreIds();
  },
};

Upvotes: 1

Views: 50

Answers (1)

macghriogair
macghriogair

Reputation: 1481

Since you are fetching data from the db asynchronously, the data will be empty until the db call was completed. You should read the data after the Promise has been resolved. (reformulating my comment as answer).

One way to do it, could be to return the Promise from readMatches:

    export default {
  data() {
    return {
      matchData: [],
    };
  },
  methods: {
    readMatches() {
      return db.collection("matches")
        .get()
        .then((queryMatchSnapshot) => {
          queryMatchSnapshot.forEach((doc) => {
            // this.matchData = []; // <= why would you reset it in each loop?
            this.matchData.push({
              awayscore: doc.data().awayscore,
              homeScore: doc.data().homeScore, 
              matchScores: doc.data().matchscores,
            })
          });
          console.log(this.matchData[0].matchScores[0])
        });
      },

      readMatchPlayerScoreIds() {
          console.log(this.matchData[0].matchScores[0])
      }
  },
  mounted() {
    this.readMatches()
        .then(() => this.readMatchPlayerScoreIds());
  },
};

But it depends on what you want do to in readMatchPlayerScoreIds method body.

Also, be aware not to reset matchData in the forEach loop.

Upvotes: 2

Related Questions