CIS-2450 Lab #8: Web APIs

Reading: The website for the official NASA APIs gives you information on the APIs and a place to create an API key (if you need one).

Part 1: Creating the App

  1. Begin by starting with your last lab commenting out all references to the Markdown editor component. Because of the way in which JSX is parsed, you will need to escape to JavaScript and use JavaScript block comments to comment out the use of the editor component. This is done by enclosing the component in {/* ... */} pairs.

  2. On the NASA APIs website, look up the documentation for the Astronomy Picture of the Day (APOD) API. Try fetching today's APOD using its API on the Postman website (you may have to create a free account on the site first). Most likely the DEMO_KEY will work, but it only allows a very limited number of requests from a particular IP address per day, so you might want to get a real app key from NASA (also free). NOTE: Be careful not to paste a trailing newline into Postman's query box. The server will take the newline as part of the key, rendering it invalid.

    Try to fetch the APOD for a different day to verify that you understand how to set up the request.

  3. Write a function named ImageDisplay in App.jsx that accepts a JavaScript object with a selectedDate member and returns an HTML img element with the src attribute set to some constant image located anywhere on the web (the point is to see if you can get an image to display at all). For example:

        const ImageDisplay = ({ selectedDate }) => {
          // No use of the selectedDate parameter yet.
          return (
            <img src="https://apod.nasa.gov/apod/image/2411/NGC6744_V2_8_sm1024.jpg"
                 alt="APOD"/>
          );
        };
      

    Invoke this component where the Markdown editor used to be using today's date as the value of the selectedDate attribute (using new Date() will create a Date object initialized with the current date). Verify that the application works as expected. The calendar should still be there.

  4. In preparation of the next step, you will need to create some state inside ImageDisplay to hold the image URL.

            const [imageUrl, setImageUrl] = useState(null);   // State to hold the image URL
            const [isLoading, setIsLoading] = useState(true); // State to hold the loading status
    
      

    The first state variable (imageUrl) holds the URL of the image. The second state variable (isLoading) is true while the API call is executing.

  5. To make the API call it is necessary to use useEffect. Here is a skeleton:

      useEffect(() => {
        const fetchData = async () => {
            try {
                setIsLoading(true);
                const response = await fetch("https://api.example.com/data");
                const data = await response.json();
                console.log(data);
            } catch (error) {
                console.error("Error fetching data:", error);
            } finally {
              setIsLoading(false);
            }
        };
    
        fetchData();
      }, [selectedDate]);
      

    You must first import useEffect from 'react'. This function accepts a function as a parameter and executes it whenever the selectedDate property is changed (due to selectedDate being mentioned in the dependency array passed as a second parameter to useEffect).

    The use of useEffect should be inside the function implementing the ImageDisplay component.

    In this case, the function asynchronously fetches the proper URL (which needs to be constructed from the date and converts the response into a JavaScript object that can be used naturally in the program. You will need to replace console.log(data) with an invocation of setImageURL to update the URL used in the img element. NOTE: You might consider keeping the console log for debugging purposes.

    Note that you can format a Date object in ISO format using:

          const formattedDate = selectedDate.toISOString().split('T')[0];
        

    This converts the date to a string of the form: YYYY-MM-DDTHH:MM:SS. By splitting that string on 'T' you can break it into the date part and the time part.

  6. Use the value of isLoading to display a nice message while the API call is being processed:

        return isLoading ? (
            <p>Loading...</p>
        ) : (
            <img src={imageUrl} alt="APOD"/>
        );
      

Part 2: ???

There is no Part 2 for this lab, currently. This part is a placeholder for possible future additions to the lab.

Submission

Create a zip archive of your skeletal project, including the dist folder, and submit that archive to Canvas.


Last Revised: 2024-11-01
© Copyright 2024 by Peter Chapin <peter.chapin@vermontstate.edu>