Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>.

like image 349
Rashed Hasan Avatar asked Oct 16 '22 14:10

Rashed Hasan


1 Answers

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);
    });
  }
}
like image 118
George Hanson Avatar answered Oct 18 '22 06:10

George Hanson