Home » vue » Set ajax-fetched data to component before render

Set ajax-fetched data to component before render

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m using Vue Router with file based components. I called one of the routes CaseDetail.vue and it gets a parameter (slug) which fetches a json from an API with axios.

I’m doing this with ”In-Component Guards”, with the method called beforeRouteEnter. I’m passing the response from axios into the next-method.

    axios.get('/case/'+ to.params.slug +'.json').then((response) => {
      next(vm => {
        vm.entry = response.data;
      })
    });

Which works, but, Vue renders the view before the data gets set. Which generates undefined errors. How can I tell Vue to wait for it to get the data?

My template:

<template>
  <main>
    <h1>{{ entry.title }}</h1>
  </main>
</template>

My component:

export default{

 name: 'CaseDetail',
 data(){
    return{         
        entry: null
    };
 },

...
Answers:

Processing steps:

  1. axios api is calling
  2. component is created
  3. next() in beforeRouteEnter is called. At that time, because component is created, so vm variable is available.

If you console log in your component

  created() {
    console.log('Component is created!')
  },
  beforeRouteEnter(to, from, next) {
    setTimeout(() => {
      next(vm => {
        console.log('next() is called')
      })
    }, 3000)
  },

Then the result will be

Component is created!

next() is called

You should set default value to your data, or add a safety check.

<template>
  <main>
    <h1>{{ entry? entry.title: '' }}</h1>
  </main>
</template>