Fetch API

A Succinct and Powerful Way to Fetch Data

Fetch API

Fetch allows us to send and receive data from our browser environment thus eliminating the need for page refreshes. It is more user-friendly and powerful than its counterpart, XMLHttpRequest.


Using Fetch

Fetch allows us to make request for data as well as send data to other APIs. Let's take a look at how we put it into action.

fetch("https://swapi.co/api/people/22")
  .then(response => response.json())
  .then(jsonData => console.log(jsonData))
  .catch(err => console.log(err))

What's Happening?

First, fetch is sending a request from our browser to some API end-point. The API processes that request and, depending on the HTTP request verb, either returns information from the database (DB), adds new information to the DB, updates an entry already existing in the DB, or removes and entry from the DB. Each of these is going to return some response (usually updated data) to the requesting client.

This data can be used to do just about anything. We can add or update DOM elements, remove DOM elements, update styling, refresh a game, make a robot fly three feet to the right, etc. Anything that can be done with JS, can be done with a simple fetch.


What Else Can I Do??

This has been a pretty basic, yet powerful, example of what fetch can do. But what about those other HTTP verbs?? Well fetch can handle those as well. But that is going to take another parameter...


Initialization Object

So fetch accepts two parameters. The first is always going to be the API endpoint you are accessing. The second (optional) parameter is an initialization object. Through this object we can pass a number of configuration settings. Some of the most used are method, headers, and body. Let's explore these a bit more.

method

method refers to the HTTP request method we will be using. The default value for this is GET as you may have already guessed. But we can use any valid HTTP verb in here. Since we're using AJAX requests here, we can use ANY one we want. Usually we'll be using either POST, GET, PUT, or DELETE.

headers

headers are things that get sent before any request or response. They're essentially metadata about the req or res that we're sending. They can describe what the following content will be (Content-Type) or that the following data is encoded (Accept-Encoding) or even custom headers (This-Is-Meaningless). Headers are incredibly useful for making sure the server or browser we're sending info to is capable of processing our data.

body

This is arguably the most important one. body is what allows us to send data back to a server. This is exactly the same behavior we see with the request body of forms. We can use any corresponding values in our Controllers. Let's see an example

fetch POST

const data = {
  title: "New Blog Post - Fetch",
  content: "You're so fetch!",
}
fetch("/api/posts/add", {
  method: "POST",
  headers: {
    "Content-Type": "text/plain",
  },
  body: data,
})
  .then(res => res.json())
  .then(data => console.log(data))

Let's make this work!


How/Why would I use this?

Why would I add or retrieve data this way? How would I practically use this? Glad you asked. Using this kind of a request has a HUGE advantage over using HTML form elements. This method is a lot less memory intensive as it is only asking for a (usually) small subset of data from a DB. It's also only applying changes to a component of our DOM at any given time. fetch is also Asynchronous, which means that we can send the request based on some user interaction, let it process in the background while still interacting with our application (or even sending more requests at the same time!), and then updating only the parts of the app that are affected by the response!

Usually you will use this behavior to create Single Page Applications (SPAs). So it is rare that you will be mixing HTML forms with AJAX requests, but it does happen. But what's an SPA?


Single Page Applications

This is a paradigm different than the approach that we have been taking so far. We have been making Multi Page Applications (MPAs). This is still a totally valid way to make applications. In fact, depending on the kind of application you're making, it may be preferred. MPAs make use of full page refreshes to populate new data. Most of the time, these models are simple web sites.

Most folx use SPAs to mimic the behavior of applications. Think the kinds of applications that you use on your phones or tablets. SPAs usually have a separate backend component, usually a RESTful API, that they pull data from. This is how most React, Angular, and Vue applications function and most of them actually make use of many APIs at any given time.


Conclusion

So we've seen how we can use fetch to make dynamic queries to our own DBs as well as other third-party APIs. Hopefully it is clear that this behavior is incredibly desirable when developing applications that can quickly and adequately respond to user interaction.