ALAB 308A.4.1 - AJAX, Fetch, and Axios


Learning Objectives

By completion of this lab, learners will be able to:

  • Request data from an external API using Fetch and Axios.
  • Create an interactive, dynamic webpage that serves content from an external API.
  • Use async/await and promises to create synchronous logic in asynchronous actions.
  • POST data to and DELETE data from an external API.

 CodeSandbox

This lab uses CodeSandbox as one of its tools.

If you are unfamiliar with CodeSandbox, or need a refresher, please visit our reference page on CodeSandbox for instructions on:

  • Creating an Account
  • Making a Sandbox
  • Navigating your Sandbox
  • Submitting a link to your Sandbox to Canvas

Instructions

Your instructor may choose to have you work in pairs or small teams for this assignment.

  1. Fork this CodeSandbox and name it "JavaScript Fetch Lab."
  2. You will be working primarily within the index.js file.
  3. Take some time to familiarize yourself with the contents of the sandbox.
  4. Complete the tasks described below inside of this CodeSandbox. These tasks have also been included as comments within index.js for quick reference.
  5. Submit the link to your final CodeSandbox (which will be named "JavaScript Axios Lab"; read through the tasks below before beginning) on Canvas when you are finished.

The Cat API

For the purposes of this lab, we'll be working with The Cat API, which is a free public API. Head to the API's website and create a free account:


The first step to working with any API is exploring its documentation. Every API you work with will be different, so never make any assumptions.

Once you have generally familiarized yourself with the API, continue to the tasks below.


Getting Started

The CodeSandbox we're working with already contains a pre-configured HTML layout that includes a bootstrap carousel display. It also includes some JavaScript helper functions for working with it. Within your index.js file, be careful not to delete the import * as Carousel from './Carousel.js' statement at the top of the page. This statement will give you access to the following static functions:

  • Carousel.clear() will remove all items from the carousel display.
  • Carousel.createCarouselItem(imgSrc, imgAlt, imgId) will create and return a new element to be displayed in the carousel (but it will not add this item to the carousel automatically).
  • Carousel.appendCarousel(element) will append the provided element (which should be the return of a createCarouselItem() call) to the carousel.
  • Carousel.start() should be called after the addition of new elements to the carousel.

Using these functions will also prepare you for the inevitability of working with somebody else's code. On a development team, you will often be given unfamiliar code and slim documentation and told to make it work. The objective of this lab is not to understand how these functions work (though you should be able to - take a look at them!), but rather to understand how to put them to work with the information and requirements you've been given.


Tasks

Now that you know what you already have, here's what you need to do. These steps are best accomplished in order, but feel free to approach the problem differently if you see a creative and efficient solution:

  1. Create an async function "initialLoad" that does the following:

    • Retrieve a list of breeds from the cat API using fetch().
    • Create new <options> for each of these breeds, and append them to breedSelect.

      • Each option should have a value attribute equal to the id of the breed.
      • Each option should display text equal to the name of the breed.
    • This function should execute immediately.

  1. Create an event handler for breedSelect that does the following:

    • Retrieve information on the selected breed from the cat API using fetch().

      • Make sure your request is receiving multiple array items!
      • Check the API documentation if you're only getting a single object.
    • For each object in the response array, create a new element for the carousel.

      • Append each of these new elements to the carousel.
    • Use the other data you have been given to create an informational section within the infoDump element.

      • Be creative with how you create DOM elements and HTML.
      • Feel free to edit index.html and styles.css to suit your needs, but be careful!
      • Remember that functionality comes first, but user experience and design are important.
    • Each new selection should clear, re-populate, and restart the carousel.
    • Add a call to this function to the end of your initialLoad function above to create the initial carousel.

  1. Fork your own sandbox, creating a new one named "JavaScript Axios Lab."

  1. Change all of your fetch() functions to Axios!

    • axios has already been imported for you within index.js.
    • If you've done everything correctly up to this point, this should be simple.
    • If it is not simple, take a moment to re-evaluate your original code.
    • Hint: Axios has the ability to set default headers. Use this to your advantage by setting a default header with your API key so that you do not have to send it manually with all of your requests! You can also set a default base URL!

  1. Add Axios interceptors to log the time between request and response to the console.

    • Hint: you already have access to code that does this!
    • Add a console.log statement to indicate when requests begin.
    • As an added challenge, try to do this on your own without referencing the lesson material.

  1. Next, we'll create a progress bar to indicate the request is in progress.

    • The progressBar element has already been created for you.

      • You need only to modify its width style property to align with the request progress.
    • In your request interceptor, set the width of the progressBar element to 0%.

      • This is to reset the progress with each request.
    • Research the axios onDownloadProgress config option.
    • Create a function "updateProgress" that receives a ProgressEvent object.

      • Pass this function to the axios onDownloadProgress config option in your event handler.
    • console.log your ProgressEvent object within updateProgress, and familiarize yourself with its structure.

      • Update the progress of the request using the properties you are given.
    • Note that we are not downloading a lot of data, so onDownloadProgress will likely only fire once or twice per request to this API. This is still a concept worth familiarizing yourself with for future projects.

  1. As a final element of progress indication, add the following to your Axios interceptors:

    • In your request interceptor, set the body element's cursor style to "progress."
    • In your response interceptor, set the body element's cursor style to "default."

  1. To practice posting data, we'll create a system to "favourite" certain images.

    • The skeleton of this favourite() function has already been created for you.
    • This function is used within Carousel.js to add the event listener as items are created.

      • This is why we use the export keyword for this function.
    • Post to the cat API's favourites endpoint with the given ID.
    • The API documentation gives examples of this functionality using fetch(); use Axios!
    • Add additional logic to this function such that if the image is already favourited, you delete that favourite using the API, giving this function "toggle" functionality.
    • You can call this function by clicking on the heart at the top right of any image.

  1. Test your favourite() function by creating a getFavourites() function.

    • Use Axios to get all of your favourites from the cat API.
    • Clear the carousel and display your favourites when the button is clicked.
    • You will have to bind this event listener to getFavouritesBtn yourself.
    • Hint: you already have all of the logic built for building a carousel. If that isn't in its own function, maybe it should be so you don't have to repeat yourself in this section.

  1. Test your site, thoroughly! Debug your code as needed.

    • What happens when you try to load the Malayan breed?

      • If this is working, good job! If not, look for the reason why and fix it!
    • Test other breeds as well. Not every breed has the same data available, so your code should account for this.

Solution Demonstration

Here is a demo solution so that you can get an idea of what you're working toward.

Note that your infoDump section (task 2) can be much more evolved than this example if you have the time to expand upon it.

Your instructor will also have access to the completed CodeSandbox solution that can be used as a review tool after completion of the assignment. Code review is an important part of the development cycle; reviewing your code, the example solution, or a peer's code can help all involved solidify their understand of these concepts, provided their is time to do so.

If you do review the solution's code, do not assume it is perfect! (Hint: it isn't.) It works, but there are improvements to be made.

Can you identify a few of these potential improvements? We'll give you one for free: where's the error handling?!

Copyright © Per Scholas 2024