[Vuejs]-Can't assign fetch() data to vue property

0👍

Your code actually looks (nearly) fine. The only thing you have to consider is, that you work with Promises in the getData function. That means, that you have to return the promise in your getData function and run the consoleLog function after the Promise resolved, like this:

https://jsfiddle.net/93z4wrba/3/

new Vue({
  el: "#app",
  data: {
    name: null,
    height: null
  },
  methods: {
    getData() {
      return fetch('https://swapi.dev/api/people/1')
        .then((res) => res.json())
        .then((data) => {
          console.log(data);
          this.name = data.name;
          this.height = data.height;
        })
    },
    consoleLog() {
      console.log(this.name, this.height);
    }
  },
  created() {
    this.getData()
      .then(() => {
        this.consoleLog()
      })
  }
})

Maybe consider switching to async/await, which makes the code a bit more readable.

Leave a comment