Wait for Ajax response data in Vue.js

23,104

Solution 1

Try the code below: so the code will render only when its actually loaded

<div v-if="tools">
    This is Default child component
    {{tools[0].name}}
</div>

Solution 2

Usually for that, I am using a loader to show the user that a request is in progress

<div v-if="loading">
  <loader /> //a loader component
</div>
<div v-else>
  // show the template since request finished
</div>

and the script

export default {
  data: () => ({
    loading: false
  }),
  created() {
   this.loading = true
   axios.get('api') //your request
   .then(response => console.log(response))
   .finally(() => (this.loading = false)) //when the requests finish
  }
}

If you don't like the way above, you can use beforeEnter so the route will load only when the request finishes:

{
  path: '/my-route',
  component: YourComponent,
  props: true,
  beforeEnter (to, from, next) {
    axios.get('api-request')
     .then(response => {
      to.params.data = response //we pass data through props to the component
      next()
     })
  }
}

Solution 3

<template>
    <div v-if="isGetTools">
        This is Default child component
        {{tools[0].name}}
    </div>
</template>
<script>
import { CustomJS } from '../js/custom.js';
export default {
  name: 'HomeContent',
  props: {
    tools: []
  },
  data: function () {
    return {
      isGetTools: false
    }
  },
  methods: {
      fetchData() {
        const customJs = new CustomJS();
        this.tools = customJs.getTools();
        this.isGetTools = true;
      }
  },
  created() {
    this.fetchData(); //preferably need to wait here wait for response
  }
}
</script>

Try to add v-if in your div. And update the isGetTools to true after getting the result from AXIOS

Share:
23,104

Related videos on Youtube

Souvik Ghosh
Author by

Souvik Ghosh

Updated on July 09, 2022

Comments

  • Souvik Ghosh
    Souvik Ghosh 4 months

    I have a Vue component where I am trying to fetch some data from an API using axios.

    <template>
        <div>
            This is Default child component
            {{tools[0].name}}
        </div>
    </template>
    <script>
    import { CustomJS } from '../js/custom.js';
    export default {
      name: 'HomeContent',
      props: {
        tools: []
      },
      methods: {
          fetchData() {
            const customJs = new CustomJS();
            return customJs.getTools();
          }
      },
      created() {
        this.tools = this.fetchData(); //preferably need to wait here wait for response
      }
    }
    </script>
    

    The getTools() function is in a different JS file outside the Vue component file which makes the API call using axios.get.

    getTools(id = 0){
        this.apiTool += (id > 0) ? id : '';
        axios.get(this.apiTool, {
        })
        .then(function (response) {
            console.log(response.data);
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    }
    

    The problem is, {{tools}} is undefined since the getTools() takes some time to return the response data. How can wait for the response data and then return?

  • Eddo over 4 years
    It would also be possible to return the promise from the axios call in getTools implementation. Then you will not have to wrap it around another promise
  • Souvik Ghosh
    Souvik Ghosh over 4 years
    With this the content inside the div doesn't load.
  • Souvik Ghosh
    Souvik Ghosh over 4 years
    Sorry, there seems to be some syntax error and this code gives a build error.
  • Souvik Ghosh
    Souvik Ghosh over 4 years
    Tried your code. First approach- tools is undefined but response gets logged inside fetchData(). Second approach- I am getting a Promise<pending> inside created in my console and can see the values when I expand it to PromiseValue.
  • Dionisis Karakasiliotis over 4 years
    I forgot to close a parentheses. Give it another try
  • Souvik Ghosh
    Souvik Ghosh over 4 years
    tools is undefined, same as before
  • Hardik over 4 years
    maybe you have to assign new data source to tools from parent component. can you please share plunkr or sample for the same

Related