Harsh Raj
Harsh Raj

Reputation: 65

Vue - Cannot set property of undefined in response

<template>
<div class="address">
  <h1>{{address}}</h1>
</div>
</template>

<script>

export default {
    data() {
        return {
            id: this.$route.params.id,
            address:''
    }
},
created(){
 this.$axios.post("http://localhost/flutter_api/action.php",{
   id: this.id,
   action: "fetchaddress"
 })
 .then(function(res) { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })
 .catch(function(error){
    console.log(error)
 })
 }
 }
 </script>

It is throwing an error like this TypeError: Cannot set property 'address' of undefined`` at eval (Address.vue?b0a0:24)

Please help me

Upvotes: 0

Views: 1380

Answers (1)

Raffobaffo
Raffobaffo

Reputation: 2856

It's because you are not binding this in the callback of your http call. You could use an arrow function for example to solve it.

from

 .then(function(res) { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })

to

 .then((res) => { 
    console.log(res.data.address); // This returns the address
    alert(res.data.address);
    this.address=res.data.address;
 })

Upvotes: 5

Related Questions