JS Tip of the Day: fetch is the new XMLHttpRequest

fetch is the new XMLHttpRequest
Level: Beginner

The introduction of XMLHttpRequest was a game changer for JavaScript on the web. It allowed websites to pull data directly from the server rather than having the user have to reload or navigate to another page. Unfortunately, as an API, it has not aged very well and can be difficult to work with. Your standard XMLHttpRequest request might have looked something like:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       // do stuff
    }
};
xhr.open('GET', 'url', true);
xhr.send(null);

A newer API for loading data now exists that’s easier to use and uses modern language features like promises. This comes in the form of the fetch() function. fetch() takes a url and returns a promise that resolves when a response from loading the url is available.

fetch('url')
    .then(response => {
        if (response.ok) {
            // do stuff
        }
    });

Despite its apparent simplicity, fetch() offers a lot more features beyond what the basic example above demonstrates. See the fetch link below for more on those features and additional examples.

More info: