Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.7 - How to retrieve data from an API with a axios.get?

I'm trying to get data from an API in a Laravel Vue component. I get this error in the console:

TypeError: Cannot set property 'continents' of undefined

What am I missing?

This is my code:

<script>
    export default {
        mounted() {
            console.log('Component mounted.');
        },
        created(){
            this.loadData();
        },
        data() {  
            return {
                continents: [],
            }
       },
       methods: {
            loadData: function() {
                axios.get('/api/continents')
                  .then(function (response) {
                    // handle success
                    console.log(response.data);
                    this.continents = response.data;
                  })
                  .catch(function (error) {
                    // handle error
                    console.log(error);
                  })
                  .then(function () {
                    // always executed
                  });
            },       
        },  
    }
</script>
like image 484
Davide Casiraghi Avatar asked Dec 24 '22 00:12

Davide Casiraghi


1 Answers

Here is the simple working demo of axios.get request

var app = new Vue({
  el: '#app',
  data: {
    users:[]
  },
  mounted(){
     this.loadData();
  },
  methods:{
     loadData:function(){
  axios.get('https://jsonplaceholder.typicode.com/users').then(res=>{
       if(res.status==200){
         this.users=res.data;
       }
     }).catch(err=>{
         console.log(err)
     });
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
 <ol>
    <li v-if="users.length>0" v-for="user in users">
      {{ user.name }}
    </li>
  </ol>
</div>
like image 65
Saurabh Mistry Avatar answered Feb 24 '23 15:02

Saurabh Mistry