Rashed Hasan
Rashed Hasan

Reputation: 3751

How to access `PromiseValue` in axios `response` in VueJs

I am trying to show client information details in the modal. After clicking @click="showDetails(props.row.id)".

I am using axios.get in method and returning the data. Now, It's returning the data as PromiseValue object. How to access PromiseValue to show the value in HTML. Would someone help me please to solve the problem! I am trying like below -

<button @click="showDetails(props.row.id)"><i class="fas fa-eye"></i></button>

And in script-

<script type="text/javascript">
  import axios from 'axios';
  export default {
    data(){
        return{
            leftPanelVisiblity: false,
            singleData: '',            }
    },
    methods:{
        showDetails(id){
            let b = axios.get('/api/clients/'+id)
                      .then(function (response) {
                        return response.data;

                      }).catch(error => {
                            alert(error);
                      });
            //console.log(b);
            this.singleData = b;
            this.leftPanelVisiblity = true
        },
    }
  }
</script>

enter image description here

And finally, I want to access or show the data in the leftPanelVisiblity modal like -

<p>Name: {{ this.singleData.name }}</p>

Or

<p>Name: {{ this.singleData.email }}</p>.

Upvotes: 5

Views: 3386

Answers (2)

George Hanson
George Hanson

Reputation: 3040

You cannot assign the Axios call to a variable while using Promises (unless you are using await/async).

Instead you should be running the logic within the then callback. Otherwise to the synchronous nature of JavaScript it will run before the request has completed. Your code should look something like this:

methods:{
  showDetails(id){
    axios.get('/api/clients/'+row.id).then(response => {

      //Logic goes here
      this.singleData = response.data
      this.leftPanelVisibility = true

    }).catch(error => {
      alert(error);
    });
  }
}

Upvotes: 3

Eduardo Hernandez
Eduardo Hernandez

Reputation: 533

You need to assign a variable the response of your axios:

 showDetails(id){
        axios.get('/api/clients/'+id)
                  .then(function (response) {
                      this.singleData = response.data;
                  }).catch(error => {
                        alert(error);
                  });
        console.log(this.sigleData);

        this.leftPanelVisiblity = true
    },

Upvotes: 0

Related Questions