Obtain JSON data from an API and display it in a table using axios and Vue.js

I am working with a datatable and trying to populate it with data fetched from an API that returns JSON using the findAll() method from Sequelize.

However, when I call the getUser method in console.log, it shows that the data is being retrieved. But when I try to insert the data into the datatable, it indicates that there is no data available.

You can check out an example of a datatable used in the code here:

    <template>
      <div>
        <data-table v-bind="bindings"/>
      </div>
    </template>

    <script>
    import ActionButtons from "../Components/ActionButtons"
    import axios from "axios"

    export default {
      name: 'Usuarios',
      data(){
        return {
          user: this.user,
          errors: []
        }
      },
      computed: {
            bindings() {
                return {
                  data: this.user,
                    lang: "pt-br",
                    actionMode: "single",
                    columns: [
                      {
                        key:"code",
                        title:"Código"
                      },
                      {
                        key:"name",
                        title:"Nome"
                      },
                      {
                        key:"login",
                        title:"Login"
                      },
                      {
                        key:"cpf",
                        title:"CPF"
                      },
                      {
                        key:"actions",
                        title:"Ações",
                        component: ActionButtons,
                      },
                      ],
                }
            }
        },
        methods:{
          getUser() {
                          axios
                            .get("http://localhost:3005/users")
                            .then((res) => {
                              this.user = res.data;
                            })
                            .catch((error) => {
                              console.log(error);
                            });
                    },
              }
    };
    </script>

Answer №1

In my opinion, the issue arises because the getUser() method is defined but never actually called.

By shifting the asynchronous request to the created() lifecycle hook, the request will be executed before the component is mounted, ensuring that the table has access to the necessary data. More information on this can be found at this link.

Answer №2

I believe this information will be extremely beneficial to you.

    <template>
        <v-card>
            <v-card-title>
                Employee List
            </v-card-title>
            <v-card-text class="mt-3">
                <main>
                    <data-table v-bind="listing_personnel" @actionTriggered="handleAction"/>
                    <br>
                </main>
            </v-card-text>
        </v-card>
    </template>
    
    <script>
        import axios from "axios";
        import ActionButtons from "./ActionButtons"
    
        
        export default {
            data(){
                return {
                    user: [],
                    errors: []
                }
            },
            created() {
                this.getPersonnel();
            },
            methods: {
                handleAction(actionName, data) {
                    console.log(actionName, data);
                    window.alert("check out the console to see the logs");
                },
    
                async getPersonnel() {
                    try {
                        const response = await axios.get("SeletAllUsers");
                        this.user = response.data;
                    } 
                    catch (error) {
                        console.log(error);
                    }
                },
            },
    
    
            computed: {
                listing_personnel() {
                    return {
                        data: this.user,
                        actionMode: "multiple",
                        columns: [
                        { 
                            key: "user_matricule",
                            title: "Employee ID"
                        },
    
                        { 
                            key: "user_lastname",
                            title: "Last Name"
                        },
    
                        { 
                            key: "user_firstname",
                            title: "First Name"
                        },
    
                        { 
                            key: "user_contact1",
                            title: "Contact"
                        },
    
                        { 
                            key: "user_email",
                            title: "Email"
                        },
    
                        {
                            key:"actions",
                            title:"Actions",
                            component: ActionButtons,
                        },
                        ]
                    };
                }
            },
    
        };
    </script>


/* Preferably place this in its main.js
axios.defaults.baseURL = 'http://localhost:8080/';*/*

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

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

information not adhering to the text field

I'm having some trouble with Vue as I try to bind the result to a textarea: <textarea class="form-control" id="test" rows="6" v-model="test"></textarea> data: { test: '' } axios({ method: 'po ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

What is the best way to resolve an npm build error on Windows 10?

I have exhausted all options but still cannot successfully install any npm modules. Any suggestions on how to resolve this issue? Microsoft Windows [Version 10.0.17134.590] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\Dell&bsol ...

AJAX POST request encountered a 400 Bad Request Error

One of the tasks in my Spring project is to enable data updating in the database upon clicking a specific button. Currently, I have the following code set up: update.jsp : <div class="searchParentOne"> <div class="noticeBlankTwoButtons ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

Employing Isotope/jQuery for organizing posts on Tumblr in columns with the ability to infinitely scroll

Alright so, here we have the classic dilemma where scripts are running before images load. And to make matters more complicated, on Tumblr, there's no way to access image dimensions before they're loaded into the DOM... $('#thumbnails&apos ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

I want to hide jqvmap when viewing on mobile devices

I'm currently working on my website at . I have a template that I'm using as a guide, but I want to make the map disappear on mobile view and replace it with a dropdown list. Can anyone suggest what code I should use for this? Appreciate any hel ...

Tips for formatting dates retrieved from Vue.js Datepicker in Laravel

I am currently working on a project using Vuejs for the front end and Laravel for the backend. In one of my columns, I am trying to add dates using a datepicker. However, I keep encountering an error message: Error: Invalid datetime format - 1292 Incorr ...

Pull information from database based on selection made in combo box

I am attempting to populate a text box with values from a database based on the selection in a combo box. I have written the code below but it doesn't seem to be working correctly. The issue is that the value selected in the combo box is not being pas ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

What is the best way to refresh a PHP function based on a JavaScript event?

I have a website where a div tag shows all the values from a SQL database using PHP. I want to reload this div tag with a JavaScript event, such as clicking on an HTML button. Is it possible to bring back all the values from the SQL database and display th ...

HTML5 input placeholder adapts its size and position dynamically as data is being

During my interaction with the input fields on my bank's website, I noticed that the placeholder text undergoes a unique transformation. It shrinks in size and moves to the upper-left corner of the input field while I am entering information. Unlike t ...

Can phantomJS be used to interact with elements in protractor by clicking on them?

While attempting to click a button using PhantomJS as my browser of choice, I encountered numerous errors. On my first try, simply clicking the button: var button = $('#protractorTest'); button.click(); This resulted in the error: Element is ...

Express encountering a Segmentation Fault error

Recently, I've been experiencing intermittent SIGSEGV errors while running my express app with PM2. Surprisingly, the server had been working smoothly for a few weeks without any issues. The only error message I see is: App [XXX] with id [7] and pid ...

jquery target descendants with specific names

In the provided HTML code snippet, there is a main div with the class name of cxfeeditem feeditem, and it contains multiple child elements with similar class names and structure. My query pertains to extracting values from specific children within all the ...

Incorporate a variable into a function by integrating it

I'm struggling to accurately calculate the total hours needed based on the method of transportation. This code represents my initial attempt at learning how to code, diving into JavaScript for the first time. Here's my script: $(document).read ...