The basics of fetch()
Published: 2020-07-09 18:12:08

---
title: The basics of fetch()
published: true
date: 2020-05-02 03:36:15 UTC
tags: 
canonical_url: 
---

 ![The basics of fetch()](https://blog.kentonvizdos.com/content/images/2020/05/tofetchornottofetch.png)

Are you sick and tired of writing huge XMLHTTPRequests in your JavaScript code?

_Oh, you already stopped using those ages ago.. right.._

Well, somehow, fetch() never caught my attention until just recently so I've slowly started switching over to using it over alternatives as I think it is a beautiful built-in function baked directly into JavaScript!

## Compatibility

And sure, fetch() may not be the _best_ option for fetching API endpoints (cough cough THANKS INTERNET EXPLORER cough cough) and it is still unclear whether or not interviewers will care if you use it, but it sure is debated

> I’m conflicted. When I interview front-end candidates, most React devs pull in Axios for fetching JSON (instead of fetch), moment.js instead of Date objects, and want to use Bootstrap or a CSS framework instead of flexbox or grid. [https://t.co/Q3ITv7A0V5](https://t.co/Q3ITv7A0V5)
> 
> — Marc Grabanski ✌️ (@1Marc) [April 19, 2020](https://twitter.com/1Marc/status/1251693961904783360?ref_src=twsrc%5Etfw)

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Buuuut it is still fun to use. But first, we do need to clarify the Internet Explorer compatibility...

![The basics of fetch()](https://blog.kentonvizdos.com/content/images/2020/05/image.png)<figcaption>Internet Explorer has no compatibility</figcaption>

Yeahh, so it's _not_ perfect, but considering Edge has support, maybe you could just.. let IE slide and hope nobody uses a program that looks about a million years old..

![The basics of fetch()](https://blog.kentonvizdos.com/content/images/2020/05/image-1.png)<figcaption>Internet Explorer in 2020</figcaption>

_While Internet Explorer IS ugly and not commonly used,_ it is still used by a couple of people, so if you are looking to support them, you should look into third party libraries such as Axios, or keep up with XMLHTTPRequests.

## The Good Stuff: how to use it to send a GET request

So, you've made it this far. You've decided to leave Internet Explorer users in the dust. Let's get to some syntax.

```
fetch('https://www.reddit.com/.json?limit=1');
```

Simply put, this will return you a Promise statement, so lets learn how to use that:

```
fetch('https://www.reddit.com/.json?limit=1')
	.then(response => response.json());
```

Now, you've managed to parse your request into usable JSON, so lets go one step further:

```
fetch('https://www.reddit.com/.json?limit=1')
	.then(response => response.json())
    .then(data => console.log(data));
```
<figcaption>XMLHTTPRequest generated by Postman</figcaption>

Kachow! You've successfully pulled the first result from the front page of Reddit and printed the result! Now, lets look at the XMLHTTPRequest for

```
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
  	this.responseText = JSON.parse(this.responseText);
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://www.reddit.com/.json?limit=1");

xhr.send();
```
<figcaption>XMLHTTPRequest generated by Postman</figcaption>

Ew. Why right 13 lines when you could simply write 3 (ssshhh about compatibility..)???

It gets even better when you start doing other things, like POSTing

## Sending a POST request using fetch()

Do note: when using fetch(), you will not receive cross-site cookies and you won't send cookies unless you set the credentials option, which we will get to below.

```
fetch('https://myawesomeapi.example/new', {
	method: 'POST', // or GET, PUT, DELETE, etc
    headers: {
    	'Content-Type': 'application/json'
    },
    redirect: 'follow',
    body: JSON.stringify({
    	name: "this post is 10/10"
    })
}).then(response => response.json()).then(data => console.log(data));
```

Simple POST request complete! While it still isn't the prettiest, it's definitely better than whatever this is:

```
var data = JSON.stringify({"name":"this post is 10/10"});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://myawesomeapi.example/new");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.send(data);
```

Going back to sending with credentials (cookies), make sure you allow credentials on the API side in CORS. After that, you can simply add "credentials: 'include'" into the options above body (it doesn't really matter where, it just needs to be somewhere in the same object). Or, if you don't want to send credentials, you can use "credentials: 'omit'"

## Wrap Up

This was a very brief overview of the fetch() api. There is a lot more you can do with it, like uploading files, but that goes out of the basic scope of this article. If you are interested, send me a tweet @kvizdos and I'll write a more in depth post "All about fetch()" instead of "the basics." Overall, should you use fetch() over Axios or XMLHTTPRequests: it depends. Do you want to support IE? Then you need to use Axios or XMLHTTPRequest or one of the gazillion other options. If not, fetch() is a nice library built into JavaScript that requires 0 dependencies, so it can keep your code base a little bit smaller and a little bit cleaner if you care.

I hope you learned something from this post!