0
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.

Gabriel
  • 5,453
  • 14
  • 63
  • 92
  • In the `data()` definition there are too many curly brackets. Please try: `data() { return { somedata: 'hey, starting!' } },` – Dan May 03 '19 at 03:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil May 03 '19 at 05:00

1 Answers1

1

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);
}
Decade Moon
  • 32,968
  • 8
  • 81
  • 101