What is the best way to loop through an API response in Vue.js?

Hey there, I'm new to Vue and struggling with iterating through data in my template. Despite being able to log everything properly, I can't seem to render it on the page.

Here's the API URL:

https://private-922d75-recruitmenttechnicaltest.apiary-mock.com/customexercises/

I've attempted the following:

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

https://i.stack.imgur.com/BHCGY.png

https://i.stack.imgur.com/BNd4Y.png

Answer №1

Great job, you're almost there! :)

Explore this demo

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

Answer №2

Based on the API's response, the exercises array consists of objects. Therefore, in order to access the properties of these objects, you will need to iterate through the exercises array.

Example :

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>

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

Is there a way to dynamically alter a Vue component based on time? When I say alter, I am referring to one component replacing another, similar to how a carousel functions

Is there a way to make the widgets on my Vue website cycle every few seconds, like in a carousel? I want them to replace each other periodically. What is the most effective method for accomplishing this? ...

Unlock the message with Proxy Re-encryption technology

I'm completely new to encryption and am experimenting with a Node JS library called recrypt-js for Proxy Re-encryption using CryptoJS. I tried encrypting the message "test data" following the example provided, but I'm facing difficulty when tryin ...

Issues with managing multiple user sessions in express-session

I've been struggling with an issue for a few days now and haven't been able to find a solution. I've scoured forums and documentation, but nothing seems to work. I have a website built in Node.js, using express-session and passport for sessi ...

Retrieve individual item

It has been a few days since I started working on this. I am attempting to create a query that retrieves all businesses registered in a specific city. Subsequently, for each business, I aim to fetch all products associated with that business and then cons ...

Having trouble with the Quasar File Picker feature not functioning as expected in an Android

I am facing issues with selecting a file using this component in an android build. It was functioning properly on the web, but after building for android, it seems to be malfunctioning. <q-file v-model="file" label="Change Profile Picture" u ...

What is the best way to retrieve the elements stored within the 'this' object I am currently manipulating?

How can I access the elements nested within the 'this' that I am currently operating on? Below is the HTML code that I am currently working with: <div class="expander" id="edu">educational qualifications <ul class="list"&g ...

Can you identify the issue within this code that combines HTML5, CSS, and JavaScript?

I'm attempting to create a feature where, upon clicking a button, a hidden div will be revealed. However, my current implementation doesn't seem to be working. function reload(){ window.reload(); } function vis(x,z,a){ var xpar = docu ...

Translate a portion of a painting by utilizing context.putImageData()

I am attempting to gradually fill a canvas with pieces of the original image. To achieve this, I need each square of the image to be filled in iteratively on the canvas. To optimize performance, my approach involves rendering the original image onto an of ...

The babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

When the user clicks, display one div and conceal the others

https://codepen.io/leiacarts/pen/PoqRxNZ I need assistance with two specific tasks related to my website layout. Firstly, I am struggling to ensure that images displayed in the red sections remain constrained and automatically resize within the content di ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

Rows in the table mysteriously vanish when you switch to the following page

I am a beginner with React and I am currently using an addrow method to populate a table that I created using {this.state.rows.map}. The table successfully displays the values from the input fields. However, when I navigate away using the continue button a ...

The requested :id route could not be found using the findById() method in

Having trouble retrieving data using Insomnia from a specific ID in my collection. Below is the sample request URL. http://localhost:5000/todos/5dd295a49d5d7a0b7a399bbe However, when I access http://localhost:5000/todos/ without the ID, I can see all the ...

Assign the path parameter to the component key in the Route

One of the routes in my application is defined as shown below: <Route exact path="/licenses/:type?" component={Licenses} /> I want the component to re-render every time the type parameter changes. According to react-router documentation, I ...