1

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

1
  • Is this the complete error? Can you add photos object in the question itself. Commented Jan 16, 2017 at 5:41

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.