Empty Array returned in VueJS after Axios GET request | VUEJS/LARAVEL

Currently, I am working on a project for my university while also learning how to build a single page application through a Udemy course. The issue I'm facing is related to pushing data from a JSON database query named "alunos" to the front end using Vue and Axios. Although I can see the data from the database in the response when I log it, the array remains empty when trying to display it on the template. There are no console errors, but despite my efforts, I have been unable to resolve this issue.

Here is a snippet of the AlunoComponent.vue template:

<template>
<div>

    <button class="btn btn-primary btn-block">Add Novo Aluno</button>

    <table class="table" v-if="alunos">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">RGA</th>
                <th scope="col">Nome</th>
                <th scope="col">Instituição</th>
                <th scope="col">Campus</th>
                <th scope="col">Curso</th>
                <th scope="col">Semestre</th>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr>

                <th v-for="aluno in alunos" v-bind:key="aluno.id" scope="row" >1</th>
                {{alunos}}
                <td>{{aluno.id}}</td>
                <td>{{aluno.rga}}</td>
                <td>{{aluno.nome}}</td>
                <td>{{aluno.instituicao}}</td>
                <td>{{aluno.campus}}</td>
                <td>{{aluno.curso}}</td>
                <td>{{aluno.semestre}}</td>
                <td><button class="btn btn-info">Edit</button></td>
                <td><button class="btn btn-danger">Delete</button></td>
            </tr>   
        </tbody>
        </table>

</div>

This is the logic inside AlunoComponent.vue:

   <script>
    export default {

        data(){

            return {

                aluno:{
                    nome:'',
                    nascimento:'',
                    rga:'',
                    cpf:'',
                    rg:'',
                    instituicao:'',
                    campus:'',
                    curso:'',
                    semestre:''
                },
                //array for student information
                alunos:[],
                uri: '/alunos'

            }
        },

        methods:{

            loadAlunos(){

                    axios
                    .get(this.uri)
                    .then(response=>{

                    //console.log(response.data)
                    this.alunos = response.data.alunos
                }).catch(error => {
                  console.log(error)
                });
            }
        },

        mounted() {

            this.loadAlunos();
            console.log('Component mounted.')
        }
    }
</script>

If anyone could provide some guidance, I would greatly appreciate it as I am still new to Vue.js.

Answer №1

Your current table template is not correct. You should use a structure like the following:

<tbody>
    <tr v-for="student in students" :key="student.id" scope="row">
        <td>{{student.id}}</td>
        <td>{{student.rga}}</td>
        <td>{{student.name}}</td>
        <td>{{student.institution}}</td>
        <td>{{student.campus}}</td>
        <td>{{student.course}}</td>
        <td>{{student.semester}}</td>
        <td><button class="btn btn-info">Edit</button></td>
        <td><button class="btn btn-danger">Delete</button></td>
    </tr>   
</tbody>

If your current template is applied with 5 elements in the students array, it will look like this:

<tbody>
    <tr>
        <th>1</th>
        <th>1</th>
        <th>1</th>
        <th>1</th>
        <th>1</th>
        {{students}}
        <td>{{student.id}}</td>
        <td>{{student.rga}}</td>
        <td>{{student.name}}</td>
        <td>{{student.institution}}</td>
        <td>{{student.campus}}</td>
        <td>{{student.course}}</td>
        <td>{{student.semester}}</td>
        <td><button class="btn btn-info">Edit</button></td>
        <td><button class="btn btn-danger">Delete</button></td>
    </tr>   
</tbody>

Additionally, to hide the table when the students array is empty, using v-if="students" won't work because [] is truthy. You should use v-if="students.length".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor Changes with Grunt: Be Prepared for Some Waiting!

My Grunt watch task is experiencing significant delays between detecting a file change and starting to work. Output similar to the following is frequently seen: >> File "src/static/app/brandManager/addChannel.html" changed. Running "html2js:main" ...

The Bootstrap modals seem to be invisible within the Rails application

Currently, I am integrating jquery into the devise views of a sample rails application. My intention is to test it on a sample app before implementing it in a production code. The controller and view for welcome are already set up. The routes.rb file loo ...

Using Vue router to bind a class to links and highlight the active class

I am currently working on a project where I need to render a sidebar with links to different pages. The challenge I'm facing is that these sidebar items should have different styles when they are active. Unfortunately, I am unsure of how to create a b ...

Is it possible for a React blog to be included in search engine results?

As I work on building my blog using React, Node.js, Express, Sequelize, and other technologies, a question has arisen in my mind: Will search engines index my articles, or will only the homepage of my site be noticed? For instance, if I have an article ti ...

Using an AJAX request to edit a record directly without the need for a

When updating a record, I typically utilize CRUD operations and a store setup similar to the following: storeId: 'storeId', model: 'model', pageSize: 10, autoLoad: true, proxy: { typ ...

Strategies for delaying the loading of CSS when importing

import 'react-dates/lib/css/_datepicker.css' The CSS mentioned can be deferred since it is not critical. Is it possible to defer the loading of CSS when utilizing import? I found information on deferring CSS loading using <link> from Goo ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

View complex response objects in Postman as easily digestible tables

I am interested in displaying the data provided below as a table using Postman Tests. The table should have columns for product, price, and quantity, with Items listed in rows. It's important to note that there may be multiple shippingGroups within th ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

Adding various image files to the canvas

I am facing an issue with my code where I need to find images inserted by the user into a div and then combine them into one image in a canvas when the "snap" button is clicked. While I can successfully locate, position, and resize the images inside the ca ...

Exploring the integration of query parameters in Postman using mongoose

In my code, I have a driver.js file that holds a driver schema, and a driverController.js file with REST methods including GET, POST, DELETE, and PUT. What I want to achieve is to send a GET request to http://localhost:3000/drivers?available=true This re ...

When the enter key is pressed, scope.$watch() does not trigger, and location.path does not function as expected

I've encountered a peculiar problem with AngularJS that I need help with. Here's the situation: Using scope.watch to monitor text changes in a text field (searchloco). <input class="typeahead" ng-model="searchloco" data="{{varu}}" search-ba ...

Is there a Vuetify component for inputting days, hours, and minutes using v-text-field?

Is it possible to format a v-text-field to allow selection of days, hours, and minutes instead of just hours and minutes? I have been reviewing the Vuetify documentation for text-fields and came across this solution: https://vuetifyjs.com/en/components/te ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

I am converting a class component to a functional component within a React-Redux-Firebase project

I am currently in the process of rebuilding this component. Check out the updated code here Also, take a look at the project actions script here However, I'm facing an issue with rewriting mapStateToProps and mapDispatchToProps functions. The error ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

What could possibly be causing my code to execute multiple times?

Within my code, I have the following function that is triggered when the document is ready: $('#file_upload_form').submit(function(){ // show loader [optional line] //if(document.getElementById('upload_frame') == ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...