What is the best way to use Vue to fetch data from an API asynchronously in order to create a table?

My HTML Code

    <div id="app">
      <table>
        <thead>
          <tr>
            <th v-for="(header, key) in column" :key="key">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in rows" :key="row.id">
            <td>{{ row.id }}</td>
            <td>{{ row.name }}</td>
            <td>{{ row.phone }}</td>
          </tr>
        </tbody>
      </table>
    </div>

I am attempting to create a JavaScript function and link it to my Vue instance in order to retrieve data from an API, but I am facing some difficulties. The Vue framework does not seem to be working properly within my HTML code. Here is the current state of my code:

var app = new Vue({
  el: "#app",
  data: {
    column: {
      id: "ID",
      name: "Full Name",
      phone: "Phone",
    },
    rows: [
      { id: "", name: "", phone: "" },
    ],
  },

  methods: {
    async fetchData() {      
      const response = await fetch("https://jsonplaceholder.typicode.com/users");      
      const finalRes = await response.json();
      this.rows.id = finalRes.id;
      this.rows.name = finalRes.name;
      this.rows.phone = finalRes.phone;
    },    
  },
  mounted() {
    this.fetchData();
});

Expected Output:

ID Full Name Phone

1 Leanne Graham 1-770-736-8031 x56442

2 Ervin Howell 010-692-6593 x09125

3 Clementine Bauch 1-463-123-4447

4 Patricia Lebsack 493-170-9623 x156

5 Chelsey Dietrich (254)954-1289

6 Mrs. Dennis Schulist 1-477-935-8478 x6430

7 Kurtis Weissnat 210.067.6132

8 Nicholas Runolfsdottir V 586.493.6943 x140

9 Glenna Reichert (775)976-6794 x41206

10 Clementina DuBuque 024-648-3804

Answer №1

finalRes is actually an array of objects, so you cannot access its properties using dot syntax like finalRes.id or finalRes.name. Instead, assign the entire finalRes array directly to your rows data like this: this.rows = finalRes;

var app = new Vue({
  el: "#app",
  data: {
    column: {
      id: "ID",
      name: "Full Name",
      phone: "Phone",
    },
    rows: [],
  },

  methods: {
    async fetchData() {      
      const response = await fetch("https://jsonplaceholder.typicode.com/users");      
      const finalRes = await response.json();
      this.rows = finalRes;
    },    
  },
  mounted() {
    this.fetchData();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <thead>
      <tr>
        <th v-for="(header, key) in column" :key="key">{{ header }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="row in rows" :key="row.id">
        <td>{{ row.id }}</td>
        <td>{{ row.name }}</td>
        <td>{{ row.phone }}</td>
      </tr>
    </tbody>
  </table>
</div>

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

Tips for altering the color of a specific bar in the Material UI BarChart component

I have implemented the following code to generate a Graph: const namesArray = Object.values(tableData).map(item => item.name); const valuesArray = Object.values(tableData).map(item => item.value); return ( <Box> <SimpleCard ti ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

I encountered an error while attempting to import a file into Firebase Storage

I've been struggling to upload files from Firebase Storage and encountering errors despite reading the documentation and various blogs on the topic. I'm looking for the most effective approach to resolve this issue. import { storage } from ' ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Filtering data in JavaScript arrays involves selecting certain elements based on

I have successfully implemented an array filter using JavaScript and lodash. I am now looking to combine arrays of arrays into a single array. Can anyone provide guidance on how to achieve this? Sample Input const inputData = [ [ { 'Tempe(C)&a ...

Embed the aspx file within the background-image attribute similar to how an image source is

Within my asp.net application, there is an image tag linking to another aspx file in the src attribute, displaying a picture. <img src="/picture.aspx?Param=3" alt="picture"/> I need to convert the image tag into a div with a background-image proper ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

AngularJS allows for editing elements in an array, but not string objects directly

I am a beginner in AngularJS, currently in the learning phase. Query I want to edit a specific rma from the list. When I click on the edit button and call the controller function updateRma(rma), after selecting rma number 11, my absolute URL is "http://l ...

Despite successful installation, node remains elusive on Ubuntu VPS

After installing node using NVM with version 0.25.0, I specifically installed node version 0.10.32. However, upon running node -v, the following error is displayed: -bash: /root/.nvm/v0.10.32/bin/node: No such file or directory Similarly, when executing ...

Ways to extract information from a JavaScript popup window before it closes

I am currently facing the challenge of detecting the existence of a form field in a closed popup window. Unfortunately, I do not have control over the child window, but it is within the same domain as the parent window. I have explored the possibility of ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...

The response from the ajax call is still pending

I am currently working on integrating MySQL data (select query) using Spring and MyBatis. I have a controller function that is called via ajax in JavaScript to retrieve the database data. For example: ajax url: /testmysql controller requestmapp ...

Introducing a variety of services into the system

From my understanding, services must be provided and injected, meaning each service needs to be placed inside the constructor like this: constructor (private a: AService, private B: BService) {} In my scenario, I have multiple services that all follow th ...

Modify the information being retrieved from a promise

Within my application, there is a service that the controller calls upon to retrieve an array of objects. However, not all of the data returned by this service is relevant to my needs. I am interested in extracting only specific information from the array. ...

Are Global variables supported in the EXT JS framework?

When working with Java and C++, it is common practice to store a variable globally so that its value can be accessed from anywhere within the project. For example, if I am working inside a class named Residence and saving an INT as the residenceNumber to a ...

An error has occurred: Unable to access the 'map' property of undefined in Angular 4

I'm looking to integrate chart.js into my Angular 4 project. The plan is to retrieve data from a JSON file and display it on a graph. Everything seemed fine during compilation, but upon opening it in Chrome, I encountered an error stating "cannot read ...

Error in HTML: Text variable is not displaying the number value

Currently, I am facing a challenge with my code. I have a variable named "Timer" that I want to increment by one and then display the number. However, I am unable to see the "Test Successful!" message displayed on the screen. Surprisingly, there are no e ...

Utilizing a JavaScript variable as an argument in Fluid URI ViewHelper: A step-by-step guide

I am trying to create an Ajax call from a Fluid template using the Fluid URI action ViewHelper. However, I am facing an issue where one of the arguments needs to be dynamically obtained from a Javascript variable. How can I ensure that the ViewHelper is re ...

Vue.js watcher doesn't get triggered when value is manually assigned

I'm currently working on a Vue component that looks like this: methods: { ... toggleTyping: function () { this.composing = !this.composing; }, ... }, data: function () { return { composing: false, }; }, watch: { composing: funct ...

Vue.js has a feature where it automatically closes the form tag within a for loop

In my Vue.js application, I have created a table where each row is a form with a submit button. This is the code snippet I am using: <div id="admin-user"> <table class="table"> <tr v-for="(user, index) in users"> < ...