0

I'm trying to set my empty object with the values I get from my server API, which is a json. But I keep getting an error on the same row, over and over again:

Uncaught (in promise) TypeError: Cannot set property 'itemListModel' of undefined at eval

my code:

data: function() {
return {
itemListModel: {}
}
}

methods: {
   getAllItemsFromDb: async () => {
    const url = 'https://localhost:44339/ListAll';
      await axios.get(url, {
    headers: {
        'Content-Type': 'application/json'
    }}).then((response) => {
         this.itemListModel = response.data
    })
    }
}

computed : {
   itemResultsFromDB: function(){

      return this.itemListModel
    }
}

Looked att this previous question: Uncaught (in promise) TypeError: Cannot set property of undefined with axios

But I can't see what I am doing differently?

Emi
  • 163
  • 1
  • 7
  • 18
  • in the question you linked the answer add `let self = this` before calling `axios` and then use the variable `self` to reference this inside of `axios.get()`, because `this` is redefined somewhere – jonatjano Jul 17 '19 at 13:38
  • How are you calling the `getAllItemsFromDb` method? – Psidom Jul 17 '19 at 13:39

2 Answers2

2

The arrow function is to blame, I believe. Convert getAllItemsFromDb to a function function:

methods: {
   getAllItemsFromDb() {
      const url = 'https://localhost:44339/ListAll';

      axios.get(url, {
         headers: {
            'Content-Type': 'application/json'
         }
      }).then((response) => {
         this.itemListModel = response.data
      })
   }
}
mbojko
  • 13,503
  • 1
  • 16
  • 26
1

In your getAllItemsFromDb function you are awaiting the result of axios.get(). As a result you don't need the .then() block. Try this:

getAllItemsFromDb: async () => {
  const url = 'https://localhost:44339/ListAll';
  const response = await axios.get(url, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

  this.itemListModel = response.data;
}
Malice
  • 3,927
  • 1
  • 36
  • 52