Search code examples
vuejs2vue.jsvue-resource

Display a specific element of an array after a query


I'm in trouble to display a specific element in an array with vuejs 2. After this query I obtain an array with 20 elements :

this.$http.jsonp('https://api.instagram.com/v1/users/self/media/recent/?access_token=mytoken').then((response) => {
  this.photos = response.body.data
}, (err) => {
  console.log(err)
})

If I try to display the content of {{ photos }}, {{ photos[0] }} it works but if I try to display the content of a key like this {{ photos[0].id }} it does not work and it's the same for all the others keys. The console return this error :

Error when rendering component


Solution

  • The component renders for the first time before the AJAX request has completed. Assuming you initialize photos = [] in the data function, there will be an empty array when the component is first rendered. At this point, photos[0] is undefined and photos[0].id causes a TypeError.

    To get round this, use v-if to only render when the objects you are trying to access exist.

    <!-- only render if photos contains at least 1 item -->
    <div v-if="photos.length">
      {{photos[0].id}}
    </div>