Home > Net >  Vue won't render data for specific API request
Vue won't render data for specific API request

Time:10-09

So I have next component:

<template>
  <div class="home">
    <div class="container"  v-if="data" >
      <Card v-for="result in data" :img="result.links[0]" :key="result.href"/>
    </div>
  </div>
</template>

<script>
 import Card from "../components/Card";
 import axios from "axios";
 export default {
   name: 'Home',
   components: {Card},
   data() {
     return {
       data: null,
     }
   },

   created() {
      axios.get('https://images-api.nasa.gov/search?q=mars').then(res => {
         return res.data.collection.items
      }).then(res => {
         this.data = res;
      })
    }
 }

I have problem when I render Card component because I cant pass "img" prop, console shows "Cannot read properties of undefined (reading '0')" error, which is weird because I can see that my "data" property has got right data from API, but when I try to fetch data from same API with different query param like "https://images-api.nasa.gov/search?q=jupiter" everything works correctly. So I don't know if this could be Vue internal problem or an API problem?

CodePudding user response:

You can modify your code a bit to make sure that result.links is not undefined

<Card v-for="result in data" :img="getImageLink(result)" :key="result.href"/>

Now in your methods,

        getImageLink(result) {
            if (result.links) {
                return result.links[0];
            }

            return null;
        }

This would solve your problem

  • Related