ktaro
ktaro

Reputation: 433

Can't access data property vue 3 : Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'variablename')

export default {
  data() {
    return {
      results: [],
    };
  },
  methods: {
    getData() {
      fetch("http://rb.test/api/posts/all")
        .then(function (response) {
          if (response.ok) {
            return response.json();
          }
        })
        .then(function (data) {
          // const results = [];
          // this.results = data;
          console.log(this.results);
        });
    },
  },
};
<template>
  <button class="btn btn-danger" @click="getData">Get Data</button>
</template>

Getting this error : Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'results')

Upvotes: 0

Views: 4842

Answers (1)

Tina Gordienko_Drog
Tina Gordienko_Drog

Reputation: 335

That is because of function scope. You have to use arrow function:

getData() {
      fetch("http://rb.test/api/posts/all")
        .then(response => {
          if (response.ok) {
            return response.json();
          }
        })
        .then(data => {
          console.log(this.results);
        });
    },

Upvotes: 2

Related Questions