Home > Blockchain >  can't assign fetch() data to vue property
can't assign fetch() data to vue property

Time:10-01

I'm learning fetch() and I've managed to grab some data from the Star Wars API. I want to assign the data returned to some Vue properties. However they are coming back as null.

By default I set them to null, however once the fetch has initiated the values don't update. Does anyone know why? I've been following this tutorial https://scotch.io/@bedakb/lets-build-type-ahead-component-with-vuejs-2-and-fetch-api and have assigned my data in the same way.

https://jsfiddle.net/Ltwen65g/

The JS:

new Vue({
  el: "#app",
  data: {
        name: null,
    height: null
  },
  methods: {
        getData() {
        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);
    }
  },
  mounted() {
        this.getData()
    this.consoleLog()
  }
})

CodePudding user response:

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.

  • Related