Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a response from axios in Vue

Tags:

vue.js

axios

I read all answered questions on stack overflow but still unable to figure out how to make this work.

File1.js

I send some data to server using axios ajax call as follows:

function ajaxSearchAxios(searchType,searchText){ 
    var searchResults=[];
    axios({
        method: 'post',
        url: 'ajaxSearch/',
        data: {
              searchType: searchType,
              searchText: searchText,
            },
        responseType: 'json',
      })
      .then ( function (response){
          searchResults = response.data['searchResults']; console.log('JS searchResults=',searchResults[0].value) //this prints nicely to the console
          return searchResults

      })
      .catch ( function (error){
        console.log('ajaxSearch error'); 
      });
}

File2.js

Here I have my Vue code where I want to take output of ajaxSearchAxios() and store in Vue data.

new Vue({
    el:'#id_1',
    data:{
            SearchResults:[],
    },
    methods:{
        ajaxSearch:function(searchType){
            this.SearchResults= ajaxSearchAxios('s','s1');
            console.log('VUE =',this.SearchResults[0].value)
        },
    },
});

Thanks

like image 887
Aseem Avatar asked Dec 13 '22 12:12

Aseem


1 Answers

Remember, you're dealing with asynchronous functions, so your function needs to return and handle the functionality as a Promise

function ajaxSearchAxios(searchType,searchText){ 
    return axios({ // <--- return the PROMISE
        method: 'post',
        url: 'ajaxSearch/',
        data: {
              searchType: searchType,
              searchText: searchText,
            },
        responseType: 'json',
      })
      .then ( function (response){
          return response.data['searchResults']; 
      })
      .catch ( function (error){
        console.log('ajaxSearch error'); 
      });
}

and then handle it as a promise, instead of assigning the function to value

new Vue({
    el:'#id_1',
    data:{
            SearchResults:[],
    },
    methods:{
        ajaxSearch:(searchType) => {
            // execute axios promise and on success, assign result to var
            ajaxSearchAxios('s','s1').then(result => this.SearchResults = result)
        },
    },
});
like image 133
Daniel Avatar answered Dec 18 '22 03:12

Daniel