Home » vue » how to access response data from axios response in vuejs

how to access response data from axios response in vuejs

Posted by: admin November 26, 2021 Leave a comment

Questions:

My server Api response is like this :-

{"data":{"databases":["rohit_one_test"]},"error":null,"success":true}

I’m using axios with vue js to make the call like this.

//axiosget function

import axios from 'axios';

export function axiosGet (url) {
  return axios.get(url,{ headers: {'Authorization': 'Basic token'}})
    .then(function (response) {
        return response.data.data;
    })
    .catch(function (error) {
        return 'An error occured..' + error;
    })
}

i’m calling it somewhere else like this :-

showdblist(){
      this.url=API_LOCATION+"/tools/mysql/resources/databases/"+this.domain;
      this.dbs=axiosGet(this.url);
      console.log(this.dbs);

}

when i log the dbs variable it has something like this.

screen shot here :–https://prnt.sc/kmaxbq

my question is how can i access the name of my databases in the dbs variable ?

Answers:

Well it’s a promise being returned, so your return from within the promise resolve does nothing. Instead, treat it as a promise that’s returned, and resolve from it like:

async showdblist() {
    this.dbs = await axiosGet(this.url)
    // now this.dbs is correct
}

If you can’t use async/await just treat it like a regular promise:

axiosGet(this.url)
    .then((response) => {
        this.dbs = response.data.data
    })