The basics of fetch()
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
Buuuut it is still fun to use. But first, we do need to clarify the Internet Explorer compatibility...
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..
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:
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
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!