DEV Community

Cover image for go fetch()
Joshua Mayhew
Joshua Mayhew

Posted on

go fetch()

During the first phase of my studies at Flatiron School, I spent considerable time learning how to make frequent and practical use of fetch. Referring to a modern, streamlined interface by which we "access and manipulate parts of the HTTP pipeline" via JavaScript, Fetch API is instrumental in facilitating the cross-flow of information between web browsers and remote servers.

In service of this information exchange, the Fetch API provides an eponymous global method, fetch(), that asynchronously fetches resources across the network. Essentially, this fetch method is a logical means of retrieving data from an external database and returning it where it can then be manipulated and injected into the DOM without negatively impacting page load, or the time it takes for the browser to render the page.

Fetch requests span a number of types (GET, POST, PUT, PATCH, DELETE), but in covering the context of my bootcamp project, I specifically relied on GET requests.

To start, a fetch request takes a URL string as a parameter, designating the location where data can be retrieved, and is followed by two .then() methods, wherein the data can be converted into JSON and therefore possible to work with.

fetch("your chosen URL input")
      .then(response => response.json())
      .then(data => console.log(data))
Enter fullscreen mode Exit fullscreen mode

or, in the context of my bootcamp project:

fetch("https://api.teleport.org/api/continents")
  .then(resp => resp.json())
  .then(data => console.log(data))
Enter fullscreen mode Exit fullscreen mode

Breaking this process down further, the fetch relays an implicit GET request (GET requests do not need an explicit method value given) to the url and returns a response, aka promise. A successful promise eventually resolves with a response object, or rather a representation of the entire HTTP response. To actually target and access the data within, the json() method returns a second promise that resolves by parsing the response body text as JSON, after which the data can be readily worked with.

Console logging the data, you should see that it's been returned as collections of objects. In the above screenshot, you will see an object key, entitled _links, containing other nested objects. Looking further still, under object key continent:items, there is an array of additional objects.

Image description

Image description

Now, still using the above-demonstrated fetch() method, we can code out what we want to do with the fetched data within the second .then(). For my project purposes, I sought to append the nested continent name values to the DOM using the forEach() array method. Specifically, I iterated through the returned JSON object values and assigned each continent name to a newly created DOM element and appended it to the DOM. This entire process can be handled within the second .then(). (See below code snippet for an approximate example).

fetch("https://api.teleport.org/api/continents")
  .then((resp) => resp.json())
  .then((data) => {
    console.log(data);
    const body = document.querySelector("body");
    const continentWrapper = document.createElement("div");
    const continentList = data._links["continent:items"];

    continentList.forEach((cont) => {

      const continentName = document.createElement("p");

      let continent = cont.name;

      continentName.textContent = continent;

      continentWrapper.append(continentName);
      body.append(continentWrapper);
    });
  });

Enter fullscreen mode Exit fullscreen mode

In my final project code, I ended up abstracting functionality and handling many tasks via callback functions, but for ease of demonstrating how fetch can both retrieve external data and handle DOM manipulation, this code is a clear snapshot. First, I target the existing body element and assign it to a variable. Next, I create a div element and assign it. Then, I use object . and bracket notation to traverse the nested data objects and arrive at the list of continents. Finally, I use the forEach array method to handle creating new DOM elements to which I can append the individual continent name values to and ultimately append to the DOM.

Although there is so much more you can do with fetch and DOM manipulation, I hope this is a clear and helpful introduction to using the fetch method and accessing external data. Now, it's time to go fetch()!

Resources:

  1. “Fetch API - Web Apis: MDN.” Web APIs | MDN, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.
  2. "JavaScript Fetch API: JavaScript Tutorial https://www.javascripttutorial.net/javascript-fetch-api/

Top comments (0)