Skip to content
Advertisement

How do I initialize a default “data” value to the returned value of a callback function?

I am running into an issue being able to initialize a value on App.vue to the result of a function when that function is async. I also tried setting it to the resolution of a promise but that didn’t seem to work either. In the former case I just get an undefined value, and in the second I just get the ref type for a js promise. What is the proper way in Vue to initialize a variable to the result of a callback that will complete at a later time?

Advertisement

Answer

I prefer to do this in the created lifecycle hook. Once the async action is complete, the result is stored in the data prop.

new Vue({
  el: "#app",
  data: {
    asyncData: null
  },
  created() {
    const url = 'https://jsonplaceholder.typicode.com/posts/1';
    axios.get(url).then(response => {
        this.asyncData = response.data;
    });
  }
})

Template:

<div id="app">
    {{ asyncData }}
</div>

Here is a fiddle

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement