Tim
Tim

Reputation: 187

VueJS - Iterating over data returned from an AJAX call

I'm trying to use v-for with a mounted() that queries Instagram's API in order to display thumbnail images from a user page. I can successfully log the correct data to the console, but for some reason the v-for isn't displaying anything from the returned data.

Here's my component

<template>
  <div class="container">
    <div class="row -border-top">
      <div v-for="(post, index) in posts" :key="index">
        <img v-bind:src="post.images.thumbnail.url">
      </div>

    </div>
  </div>
</template>

<script>

export default {
  data: function() {
      return {
        posts: ''
      }
  },
  mounted: function() {
      $.get( "https://api.instagram.com/v1/users/self/media/recent/?access_token=[token]", function( data ) {
        console.log(data.data); // works
        this.posts = data.data;
      });
    }
  }
</script>

As you can see, the data is correctly returned in the console: enter image description here

Any help would be much appreciated.

Upvotes: 3

Views: 690

Answers (2)

Alex
Alex

Reputation: 4266

You need edit it with

<template>
  <div class="container">
    <div class="row -border-top">
      <div v-for="(post, index) in posts" :key="index">
        <img v-bind:src="post.images.thumbnail.url">
      </div>

    </div>
  </div>
</template>

<script>

export default {
  data: function() {
      return {
        posts: ''
      }
  },
  created() {
      $.get( "https://api.instagram.com/v1/users/self/media/recent/?access_token=[token]", function( data ) {
        console.log(data.data); // works
        this.posts = data.data;
      });
    }
  }
</script>

It worked with me, hope it help you :)

Upvotes: 0

tony19
tony19

Reputation: 138276

Computed properties must be return a value synchronously. The AJAX call within the computed property returns a value from the callback, but that return is asynchronous and thus cannot update the computed property.

I don't think a computed property makes sense here. Instead, I would recommend fetching the data in the mounted() hook, and have the AJAX callback store the received data in a data property (this.posts = data.data;).

demo

Upvotes: 3

Related Questions