Errol Boneo
Errol Boneo

Reputation: 57

Render data from an API into a Vue Template

I am successfully fetching api in vue but how to properly render it? "undefined id of null" is what I get in console error

this is the axios call I made

  axios.getOrder(id).then(response => {
    this.cart_content = response.data
    console.log(this.cart_content)
  })

this is how I'm trying to render in in vue

       <div v-if="cart_content">
          <ul v-for="i in cart_content" :key="i.id">
            <li>
              <p>{{i.name}}</p>
              <p>{{i.items.quantity}}</p>
              <p>{{i.items.unit_price}}</p>
            </li>
          </ul>
        </div>

the API is available when I console.log, it looks something like this.

id:'',
data:array[1]

the "data array" is where the details I need, can anyone tell me how to get these data.

Upvotes: 1

Views: 742

Answers (3)

Errol Boneo
Errol Boneo

Reputation: 57

Apparently my code is not wrong after all I just had to include the name of the array of object from the response to get what I wanted (cart_content.data) in v-for thanks for helping me out here guys I appreciate your time

Upvotes: 0

Miguel
Miguel

Reputation: 26

methods: {
getsomething(){
var apicall = axios.get("https://jsonplaceholder.typicode.com/users");
apicall.then(resp => {
for(var x = 0; x < resp.data.length; x++){
for(var dataCount = 0; dataCount < resp.data.length; dataCount++)
{
if(resp.data[dataCount].id == resp.data[x].id)
{
this.cart_content = resp.data[x].id;
}
}
}
})
}
}
<template>
<div>
  <div v-if="cart_content">
          <ul v-for="i in cart_content" :key="i.id">
            <li>
              <p>{{i.name}}</p>
              <p>{{i.items.quantity}}</p>
              <p>{{i.items.unit_price}}</p>
            </li>
          </ul>
        </div>
</div>
</template>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Upvotes: 0

Sunyatasattva
Sunyatasattva

Reputation: 5850

Because your data is collected in an asynchronous way, it's not initially available to your component, hence it errors out. You'll need to fetch the data on a component lifecycle method, something like this:

import axios from 'axios';

export default {
  data() {
    return {
      cart_content: [],
      id: ''
    }
  },
  created() {
    this.getOrder(this.id)
  },
  methods: {
    getOrder(id) {
      axios.getOrder(id)
        .then(response => {
          this.cart_content = response.data;
        });
    }
  }
}

Working CodeSandbox Example

Upvotes: 2

Related Questions