4.5_api_requests - MartijnKeesmaat/dating-app GitHub Wiki
API practice
XMLHttpRequest(XHR)
Is a way of retrieving data from a URL, without having to do a full page refresh. With this, you can retrieve data without interrupting the user's flow. This is often used in AJAX
.
XHR can be used to retrieve any form of data.
Simple example:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
Fetch
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
The fetch()
method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise
that resolves to the Response
to that request, whether it is successful or not.
fetch('https://dog.ceo/api/breed/poodle/toy/images')
.then(
function (response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function (data) {
console.log(data);
setDogs(data);
});
}
)
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
Fetch vs XHR
This answer made the most sense to me:
The answers above are good and provide good insights, but I share the same opinion as shared in this google developers blog entry in that the main difference (from a practical perspective) is the convenience of the built-in promise returned from fetch
Instead of having to write code like this
function reqListener() {
var data = JSON.parse(this.responseText);
}
function reqError(err) { ... }
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();
we can clean things up and write something a little more concise and readable with promises and modern syntax
fetch('./api/some.json')
.then((response) => {
response.json().then((data) => {
...
});
})
.catch((err) => { ... });
Promise
A while back I looked up what a promise is, I read some sites then thought "oh I sort of get it" and moved, but never used it since. So now I will go back and try to really understand it.
Sources
What is the difference between the Fetch API and XMLHttpRequest?