WDD 230 - Web Frontend Development I

The Fetch API

Overview

The objective of the activity is for you to work with the Fetch API and data stored in JSON format to create a page of content dynamically.

"The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network." - MDN

Prepare

We are going to use the fetch() method which requires at least one argument, the path to the resource. The fetch() method then returns an asynchronous Promise that provides a generic Response to the request.

Activity Instructions

In this activity you will build a responsive page that will display a list of the latter-day prophets.

Latter-day Prophets Card Layout Screenshot

Setup

  1. In your lesson09 folder, add a new file named "prophets.html".
  2. Add both a "styles" and "scripts" folder to the lesson09 folder.
  3. Add a file named "prophets.css" and a file name "prophets.js" into the appropriate folders.

HTML

  1. In the prophets.html file, structure the page using valid html and meta information.
  2. Link style references.
  3. Add the following HTML to your <body> element.
    <header>
      <h1>Latter-day Prophets</h1>
    </header>
    <main>
      <div id="cards"></div>
    </main>
    <footer>
      [Enter Your Name Here] | Latter-day Prophets
    </footer>

JavaScript

Mobile screenshot of the prophets.
  1. Open this file in your browser to identify and reference the key/value pairs found in the JSON data. https://brotherblazzard.github.io/canvas-content/latter-day-prophets.json.
  2. Declare a const variable named "url" that contains the URL string of the JSON resource provided.
    const url = 'https://brotherblazzard.github.io/canvas-content/latter-day-prophets.json';
  3. Declare a const variable name "cards" that selects the HTML div element from the document with an id value of "cards".
    const cards = document.querySelector('#cards');
  4. Create a async defined function named "getProphetData" to fetch data from the JSON source url using the await fetch() method.
  5. Store the response from the fetch() method in a const variable named "response".
  6. Convert the response to a JSON object using the .json method and store the results in a const variable named "data".
  7. Add a console.table() expression method to check the data response at this point in the console window.
  8. Call the function getProphetData() in the main line of your .js code to test the fetch and response.
    Example
    async function getProphetData() {
      const response = await fetch(url);
      const data = await response.json();
      console.table(data.prophets); // temporary testing of data retreival
    }
    
    getProphetData();
    Do you remember how to check the output in the console window in DevTools? Hopefully everything checks out and you see data on the latter-day prophets neatly organized in a console table view. We will comment out this line of console line of code when we are done or just remove it.
  9. If it all checks out, note that the data returns a single property, an array of objects named "prophets".
  10. Comment out the console line and call a function named "displayProphets" and include the "data.prophets" argument. Why do we send data.prophets versus just the data variable? The displayProphets() function expects an array parameter.
    Example
    async function getProphetData(url) {
      const response = await fetch(url);
      const data = await response.json();
      //console.table(data.prophets);
      displayProphets(data.prophets); // note that we reference the prophets array of the JSON data object, not just the object
    }
    
    getProphetData();
  11. Define a function expression named "displayProphets" that handles a single parameter named "prophets" somewhere in your js file. Use an arrow expression to contain statements that will process the parameter value and build a card for each prophet.
    const displayProphets = (prophets) => {
      // card build code goes here
    }
    Remember that functions are hoisted and therefore, where ever you define the function in your main line of code does not matter as it is available to the rest of the scoped code.
  12. Inside the function, use a forEach loop with the array parameter to process each "prophet" record one at a time, creating a new card each time.
    const displayProphets = (prophets) => {
      prophets.forEach((prophet) => {
    
      });
    }
  13. Inside the HTML card building loop, do the following:
    1. create a section element and store it in a variable named card using createElement(),
    2. create an h2 element and store it in a variable named "fullName",
    3. create an img element and store it in a variable named "portrait",
    4. populate the heading element with the prophet's full name using a template string to build the full name,
    5. build the image element by setting the
      1. src,
      2. alt,
      3. loading,
      4. width, and
      5. height attributes using setAttribute().
    6. Using appendChild() on the section element named "card", add the heading and image elements one at a time.
    7. Finally, add the section card to the "cards" div that was selected at the beginning of the script file.
      Example
      const displayProphets = (prophets) => {
        prophets.forEach((prophet) => {
          // Create elements to add to the div.cards element
          let card = document.createElement('section');
          let fullName = document.createElement('__'); // fill in the blank
          let portrait = document.createElement('img');
      
          // Build the h2 content out to show the prophet's full name
          fullName.textContent = `${prophet._____} ____________`; // fill in the blank
          // Build the image portrait by setting all the relevant attributes
          portrait.setAttribute('src', prophet.imageurl);
          portrait.setAttribute('alt', `Portrait of ${prophet.____} ______________`); // fill in the blank
          portrait.setAttribute('loading', 'lazy');
          portrait.setAttribute('width', '340');
          portrait.setAttribute('height', '440');
      
          // Append the section(card) with the created elements
          card.appendChild(_______); //fill in the blank
          card.appendChild(portrait);
      
          cards.appendChild(card);
        }); // end of arrow function and forEach loop
      }

Test and Style

  1. Test the output and then add the remaining information as shown in the screenshot examples.
  2. Add page styling using the external CSS file by attempting to replicate, using your own colors and font choices, the layout shown in the example screenshots.
  3. Using a CSS Grid, use the auto-fit value to ensure that the page is responsive.

    Example: ⚙ī¸ CSS Grid - Responsive Columns using autofit.
    Focus on the .grid class declarations in the CSS. Note that there are no @media queries.

Submission

  1. Update your course home page with a link to this activity.
  2. Commit and push your work to your wdd230 GitHub Pages enabled repository.