[Vuejs]-How do i iterate over API response in Vue.js?

0πŸ‘

βœ…

You are very close! πŸ™‚

See this playground

<script setup>
import { ref, onBeforeMount } from 'vue'
  
const posts = ref([])

onBeforeMount(async () => {
  posts.value = await fetch("https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/").then(raw => raw.json()).then(json => json.exercises)
})
</script>

<template>
<div v-for="post in posts" :key="post.id">
    <h2>{{ post.id }}</h2>
    <h2>{{ post.name }}</h2>
  </div>
</template>

0πŸ‘

As per the API response, exercises is an array of objects. Hence, to access it’s object properties you have to iterate over the exercises array.

Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      posts: {
        exercises:[{  
          id: "5c10de5792437a5c67e74ba2",
          name: "Pull Up",
        }, {  
          id: "5c0e7f6d41403b024ad987cc",
          name: "Barbell Bicep Curl",
        }]
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="post in posts.exercises" :key="post.id">
    <h2>{{ post.id }}</h2>
    <h2>{{ post.name }}</h2>
  </div>
</div>

Leave a comment