The Code for NasaApp


"use strict"

let $ = (id)=> {
  return document.getElementById(id);
}

let content = $("content");
let images = $("my-images");

//KEY TO ACCESS NASA API
const MyKEY = "*******************************";

let fetchBySol = async () => {
  //the user can retrieve resources by SOL number
  let sol = $("sol").value;

  //prevents the app from crashing if the user enters 0
  if($("sol").value == 0) {
    alert("Input must be greater than 0.\nTry Again!");
  } else {

    let res = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=${sol}&api_key=${MyKEY}`)

    try{

      let data = await res.json();
      
          content.innerHTML += `On Sol ${sol}, there are a total of ${data.photos.length} photos.
`; content.innerHTML += `Camera Used: ${data.photos[0].camera.full_name}.
`; content.innerHTML += `Date on earth: ${data.photos[0].earth_date}.
`; content.innerHTML += `Landing Date ${data.photos[0].rover.landing_date}.
`; content.innerHTML += `Rover Name: ${data.photos[0].rover.name}.
`; //using the map function we iterate over the photos array //and insert them inside an image element using the source //attribute data.photos.map((photo) => { images.innerHTML += `
`; }); } catch(err){ content.innerHTML += `Try another Sol.`; } } } window.onload = function() { $("find").onclick = function() { content.innerHTML = ""; images.innerHTML = ""; fetchBySol(); } }
The Code is Structured in Two Functions

The first function simply uses a return statement to grab the ID of a specific element, and return its value.

Following, we are grabbing the content, and the my-images container where we will insert the data we are trying to retrieve.

The MyKEY variable simply holds my personal key to access the Nasa Api.

Next, we declared a function called fetchBySol that uses the async keyword. This is a syntactic feature that allows for asynchronous, non-blocking pattern. For more details visit the link. async function.

Inside the fetchBySol function a few things are happening. First we get the user's input value. We make sure that if the user enters 0 the app does not crash. If the entry is valid we fetch the data using the await keyword. For more details vist async function . Inside the fetch function we used a try/catch block statement. If the response is valid, we obtain an object with the data. Then we access the object and insert the data in the content and my-images elements. If an error is encountered, we provided some feedback to the user.

Finally, once the window loads we add an event listener to the find button, and we call the fetchBySol function.