Vue is refusing to display information for a certain API call

Within my next component, I have the following structure:

<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;
      })
    }
 }

Encountering an issue when attempting to render the Card component, as I am unable to pass the "img" prop. The console displays a "Cannot read properties of undefined (reading '0')" error. It's peculiar as the "data" property contains the correct information from the API. However, when making a request to the same API with a different query parameter like "https://images-api.nasa.gov/search?q=jupiter", everything functions properly. Unsure if this is a Vue internal matter or a problem with the API itself.

Answer №1

To ensure that result.links is not undefined, a simple code modification can be made.

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

Within your methods section, include the following:

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

            return null;
        }

By implementing this adjustment, the issue can be resolved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can anyone explain how to pass a toggle state along with its onChange function in Ionic React?

Imagine I have this toggle element: <IonToggle id="IonToggleDarkMode" slot="end" checked={vars.darkMode} onChange={darkModeToggle}></IonToggle> The value of vars.darkMode represents the current state of the toggle, which is ...

Dynamic content is loaded on the page using AJAX before refreshing to retrieve new

I am using the FullPage.js plugin and attempting to enable navigation between pages using AJAX. While using .load();, I am able to retrieve the desired page. However, it seems that I need to reload fullpage.js since the loaded page is not active and the s ...

TypeScript - Issue with generic function's return type

There exists a feature in typescript known as ReturnType<TFunction> that enables one to deduce the return type of a specific function, like this function arrayOf(item: string): string[] { return [item] } Nevertheless, I am encountering difficulti ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

Issues with executing google.script.run in Google Web App

I am encountering an issue with the function I have defined in my .gs file: function doGet(e) { return HtmlService.createHtmlOutputFromFile('index') } function goToMaster() { const ss = SpreadsheetApp.getActiveSpreadsheet() const sheet = s ...

Issue with retrieving the ID of a dynamically created element with jQuery

Whenever I try to execute my function to display the id for a click event of a tag that has items appended dynamically, the alert does not show the id. Instead, it displays 'undefined'. Can anyone help me figure out where I am going wrong? Here ...

"Transforming a Vue.js method within a component into a created method: A step-by-step guide

I am currently working on a vue.js codebase where a method within the component is triggered by onclick() However, I would like this method to automatically run when the page loads instead of being called by onclick. After reviewing the vue.js documentati ...

Connect guarantees while generating template

Fetching data through a function. Establishing a connection and retrieving necessary information. Some code has been omitted for brevity. function executeSQL(sql, bindParams , options) { return new Promise(function(resolve, reject) { ... resolv ...

Is there a method to bypass the need for app.get() for each static file in express?

As I delve into using express.js, I'm faced with the task of serving numerous static files from my server - whether it's a .css, .jpg, .svg, .js, or any other file type. Is there a way to accomplish this without having to manually use app.get() f ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

Encountered a Error: [$injector:modulerr] while integrating Angular JS with the mysterious Planet 9

I encountered an error after implementing AngularJS in Planet 9. Planet 9 is a tool built on top of SAP UI5, offering drag and drop functionality as well as the ability to include HTML, CSS, and JavaScript. I needed to use ng-repeat for an application, so ...

The Axios.catch method does not handle network or console errors

Utilizing React with axios and redux-promise poses a challenge when it comes to handling 404 errors. See the example below: https://i.sstatic.net/Ui3wB.png This is the snippet of code causing the issue: const url = FIVE_DAY_FORECAST_URL.replace("{0}", ...

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...

The issue of a non-functional grid with scroll in a flexbox

I've encountered a problem while working with the grid layout using divs and flexbox. The header, which I want to be fixed, is overlapping with the first row and I'm struggling to get the scrolling behavior right. How can I address this issue? I ...

Google Maps API is successfully loading from an HTML file, however, it is not functioning properly when accessed

I am facing an issue while trying to connect to the Google Maps API through an AngularJS application on my localhost. Despite finding the javascript file in the HTML and displaying 'test1' in the console, the `initMap` function is not being calle ...

Tips for effectively injecting retrieved API response data into a Table

Creating a google-map with customized markers that are logos of companies is the goal. Obtaining a json file from the APIs containing the vessels of interest has been successful. The challenge faced is injecting these vessels into a table on the user inte ...

Cut off all information beyond null characters (0x00) in Internet Explorer AJAX responses

When using Internet Explorer (IE6, IE7, and IE8), null characters ("0x00") and any subsequent characters get removed from ajax responses. Here's the code snippet that showcases a loop of AJAX requests: var pages = 10; var nextnoteid = 0; for (isub ...