logo
logo

Data Fetching Cheatsheet

Fetching External APIs with the Fetch API

The Fetch API is a modern, built-in method in most modern browsers used for making network requests. It provides a cleaner interface for making HTTP requests and receiving data than the older XMLHttpRequest (XHR) API. Here's an example of how to use the Fetch API to access the Star Wars API and retrieve planet names:

fetch('https://swapi.dev/api/planets/')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
The
fetch()
method takes a URL string as its argument, and returns a Promise that resolves to a Response object. We then call the
.json()
method on the Response object to convert the response to JSON. The resulting data is passed to the second
.then()
method as an argument, where we can do whatever we want with it. If there's an error, the
.catch()
method will log the error to the console.

Accessing Data in a Response Object

When we make a request with the Fetch API, the server responds with a
Response
object. We can access the data in this object by using the
.json()
method to convert the data to a JavaScript object. Here's an example of how to access the data in the Response object:
fetch('https://swapi.dev/api/planets/')
  .then(response => response.json())
  .then(data => console.log(data.results))
  .catch(error => console.error(error));

This code will log an array of planet objects to the console.

Using Promises to Handle Asynchronous Data

The Fetch API returns a Promise, which allows us to handle asynchronous data in a more elegant way than using callbacks. When we call the
fetch()
method, it returns a Promise that resolves to a Response object. We can use the
.then()
method to handle the data when it's ready, and the
.catch()
method to handle errors. Here's an example:
fetch('https://swapi.dev/api/planets/')
  .then(response => response.json())
  .then(data => {
    // do something with the data
  })
  .catch(error => console.error(error));

Manipulating DOM Elements with Fetched Data

We can manipulate DOM elements with fetched data by creating new elements and adding them to the DOM. Here's an example of how to create a new
div
element and append it to the
body
:
const newDiv = document.createElement('div');
newDiv.setAttribute('class', 'my-class');
document.body.appendChild(newDiv);
In this example, we create a new div element with the
createElement()
method, set its
class
attribute with the
setAttribute()
method, and append it to the
body
with the
appendChild()
method.

Ternary operator in ES6

The ternary operator is a concise way of writing an if-else statement. It is commonly used in place of an if-else statement when you only need to execute one statement in each case. For example, instead of using an if-else statement to determine whether to display a population value, you can use the ternary operator.

population === 'unknown' ? 'Population' : percent.toLocaleString()

Here, the ternary operator evaluates whether the population value is "unknown". If it is, it displays the string "Population". If it is not, it returns the result of the function percent.toLocaleString().

Looping and Automation with Fetch

In this example, we use the fetch function to get data from the Star Wars API. We then use a for...of loop to loop over the results and invoke a function on each iteration to generate a new div element for each planet.

fetch('http://swapi.dev/api/planets/')
  .then(response => response.json())
  .then(data => processPlanets(data.results));

function processPlanets(planets) {
  for (const planet of planets) {
    populatePlanet(planet);
  }
}

Here, the fetch function retrieves data from the Star Wars API, and then we use two .then() methods to work with the returned data. The processPlanets function takes in the array of planet objects and loops through each one using a for...of loop. Inside the loop, we invoke the populatePlanet function and pass in the current planet object.

Using Data Attributes in HTML5

Data attributes in HTML5 allow you to store extra data in your HTML elements. They are specified with the data- prefix, followed by a custom attribute name. For example:

<div data-id="1" class="planet">Planet 1</div>

Here, we have created a custom data attribute called "id", and assigned it the value of "1". This data can then be accessed with JavaScript and used to manipulate the element or its content.

The Difference Between querySelectorAll and getElementsByClassName

The querySelectorAll method and getElementsByClassName method are used to select elements by their class name. However, there is a key difference between the two methods: querySelectorAll returns a NodeList, while getElementsByClassName returns an HTMLCollection.

NodeList
and
HTMLCollection
are both array-like objects in JavaScript that represent a collection of HTML elements. However, there are some differences between them.
  • Live vs. Static: One of the main differences between
    NodeList
    and
    HTMLCollection
    is that
    HTMLCollection
    is live, while
    NodeList
    is static. This means that
    HTMLCollection
    reflects the current state of the document, and any changes made to the collection will be immediately reflected in the collection.
    NodeList
    , on the other hand, is static and does not update automatically. If you modify the DOM after creating a
    NodeList
    , it will not automatically update to include the new elements.
  • Properties and Methods:
    NodeList
    and
    HTMLCollection
    have some different properties and methods. For example, a
    NodeList
    has a
    forEach()
    method that can be used to iterate over its elements, while
    HTMLCollection
    does not have a
    forEach()
    method.
    HTMLCollection
    , on the other hand, has a
    namedItem()
    method that can be used to retrieve an element from the collection by its
    name
    attribute.