how to asynchronously fetch the data from api using vue to form a table?

My html

    <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’m trying to write a function in js and hook it up to my vue instance to fetch the data from a api but I don’t know how. Vue even not working in my html.
It is my code now

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 outcome:

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

>Solution :

finalRes is an array of objects, so you can’t use dot syntax like that finalRes.id; finalRes.name; etc. Just assign full finalRes array to your row data like that 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>

Leave a Reply