Search code examples
vue.jsaxiosrender

Fetch each object from API data using vue and axios


This is my script that calls axios and fetch data as posts

<script>

import axios from 'axios'


export default {
  name: 'App',

  mounted: function () {
    axios.get('API URL')
      .then(response => this.posts = response.data)
  },


  data() {
      return {
        posts: null
      }
    },


};

</script>

My code on view that tries to fetch data as posts from the script above

<template>
  <div id="app"> 
    <ul>
      <li v-for="post in posts" v-text="post.createdAt"></li>
    </ul>
  <div>
</template>

SAMPLE data fetched from API URL look like this

POSTS OBJECT VARIABLES

I am able to fetch API DATA in console log as an array but when I call one object from array which is createdAT, v-text = "post.createdAt" does not print/fetch list of createdAt date list.


Solution

  • Just solved it following this document USING AXIOS TO CONSUME API here is the link for that https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html .

    Above code that I have posted works fine. Problem was on my API URL which was nested inside data[data[object]]. So the way I called data from that API

    from this

     mounted: function () {
        axios.get('API URL')
          .then(response => this.posts = response.data)
      }
    

    to this

     mounted: function () {
        axios.get('API URL')
          .then(response => this.posts = response.data.data)
      }