Gabriel
Gabriel

Reputation: 5734

How to update Vue component's property with fetched data

Vue.component('test', {
  template: `some html`,
  data() {
    {
      return {
        somedata: 'hey, starting!'
      }
    }
  },
  methods: {
    fetchdata: function fetchdata() {
      fetch('http://localhost:5000/getmesome')
        .then(response => response.json()).then(data => this.somedata = data
        );
    }
  }, created() {
    this.fetchdata();
    console.log(this.somedata); //returns 'hey starting' not the fetched data.
  }
});

As shown in the code comment, this is not refreshing the property with the fetched data. How can I do it?

Thanks.

Upvotes: 0

Views: 694

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

fetchdata() will return immediately while the request is still in progress since it is an async operation. console.log(this.somedata) will be executed before the fetch operation has completed.

This is a basic async misunderstanding; I would suggest you read up on asynchronous JavaScript topics (promises, async and await, etc).

Either of these solutions will work:

methods: {
  fetchdata() {
    return fetch('http://localhost:5000/getmesome')
      .then(response => response.json())
      .then(data => this.somedata = data);
  }
},

created() {
  this.fetchdata()
    .then(() => console.log(this.somedata));
}
methods: {
  async fetchdata() {
    const res = await fetch('http://localhost:5000/getmesome');
    const data = await res.json();
    this.somedata = data;
  }
},

async created() {
  await this.fetchdata();
  console.log(this.somedata);
}

Upvotes: 1

Related Questions