Rei
Rei

Reputation: 323

Data not showing on vue.js component using laravel api

I'm trying to get the data from database using an API, but there are no output on my vue controller.

Am I doing this right?

I think I'm assigning the scheduleList the wrong way.

I'm very new to vue.js and API, I want to know what I'm doing wrong here.

Controller

public function schedules(){ 
    return Schedule::all(); 
}

api.php

    Route::get('schedules', 'CalendarController@schedules');

Vue Component

    <script>
    import axios from 'axios'
    
    export default {
    
      data() {
        return {
          schedules: [],
    
          scheduleList: [
             {
            id: schedules.id,
            title: schedules.title,
            category: schedules.category,
            start: schedules.start,
            end: schedules.end
            },
          ],
    
        };
      },
     
      methods: {
       
        loadSchedules() {
         axios.get('/api/schedules')
         .then((response) => {
           this.schedules = response.data;
         })
         
        }
      },
      mounted() {
        this.loadSchedules();
      }
    };
    </script>
    <style>
    </style>

Upvotes: 0

Views: 623

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

The issue is in your data option because you're referencing schedules which is undefined, I'm sure that you're meaning this.schedules but doing that will not solve the issue because at first rendering this.schedules is an empty array, another problem that you're referencing at as object in scheduleList items using schedules.id, if the schedules property is an array i recommend the following solution :

<script>
import axios from 'axios'

export default {

  data() {
    return {
      schedules: [],

      scheduleList: [],

    };
  },
 
  methods: {
   
    loadSchedules() {
     axios.get('/api/schedules')
     .then((response) => {
       this.schedules = response.data;
  
      let schedule=this.schedules[0]
     
    this.scheduleList.push({
        id: schedule.id,
        title: schedule.title,
        category: schedule.category,
        start: schedule.start,
        end: schedule.end
        })

     })
     
    }
  },
  mounted() {
    this.loadSchedules();
  }
};
</script>

Upvotes: 1

Deniz
Deniz

Reputation: 1503

always catch errors if you do promises.

loadSchedules() {
     axios.get('/api/schedules')
     .then((response) => {
       this.schedules = response.data;
     })
     .catch(error => {
       console.log(error)
     })

inside your error you can better see whats going wrong. other way is the "network" tab in your browser where you can trace your api requestenter image description here

Upvotes: 0

Related Questions