Search code examples
apivue.jsaxiosv-for

VueJS Axios API, trying to get only 1 result, not many


I'm trying to get only 1 response from the Nasa images API using VueJS and Axios. I've followed the tutorial here(https://www.youtube.com/watch?v=GiIQce7Rx4Y&t=939s) and the app is working just like shown. But this tutorial shows how to get the complete list of images available through this API, I only want the first image but can't figure out how.

Here's the code for the api component:

<template>
 <div class="search">
  <section id="sectionB">
   <h2>Type in your search term</h2>
   <form v-on:submit.prevent="getResult(query)">
    <input type="text" placeholder="Type in your search" v-model="query" />
   </form>
   <br/>
   <div v-if="results">
    <div v-for="result in results" v-bind:key="result">
     <img v-bind:src="result.links[0].href" class="imgContainer" />
    </div>
   </div>
  </section>
 </div>
</template>

<script>
 import axios from "axios";
 export default {
  name: "search",
  data() {
   return {
    msg: "Search",
    query: "",
    results: "",
     };
   },
  methods: {
   getResult(query) {
    axios.get(
      "https://images-api.nasa.gov/search?q=" + query + "&media_type=image"
    )
    .then((response) => {
      console.log(response.data.collection.items);
      this.results = response.data.collection.items;
    });
   },
  },
 };
</script>

I tried removing f-for to stop the loop but that removed all images, not just everyone after the first.


Solution

  • You should refer to the documentation of the API on the website of Nasa: https://images.nasa.gov/docs/images.nasa.gov_api_docs.pdf. The only endpoint they have that returns images is the search endpoint that you are using.

    However, reading your question again.. You can just show the first of the list (array) of results: results[0], like below:

       <div v-if="results">
         <img v-bind:src="results[0].links[0].href" class="imgContainer" />
       </div>