Understanding Fetch in JS

Understanding Fetch in JS

·

2 min read

Imagine you would like to play with the pets and you throw a ball to your dog. What will the dog do. The dog will go and fetch the ball and bring it back to us. If it doesn't find the ball then it will come empty-handed. This is an analogy of how fetch works.

We use the fetch Web API (or fetch API) to make a request to a server (which could be ours or an external one, for example, a Weather API) to retrieve some information without reloading the page.

Untitled.png

This is the basic syntax of fetch.

It will send a request (sometimes called AJAX request or XMLHttpRequest for historical reasons). This request will go to the Internet, reach the URL you specified and finally come back to you with the response (result) from that URL.

It is important to understand that fetch always returns a promise. Then, we need to resolve that promise.Thus, we are adding a .then() after the fetch call to resolve the promise.

fetch(URL)
    .then(response => {
        console.log(response); 
    });

From the above code, fetch(URL) is returning a promise, and we are resolving that promise using a .then(callback). This callback that we have specified will run after sometime in the future when our fetch request has been completed. Here response is the first argument of our callback. We can name that anything but its recommended to use response.

Every time we send a fetch request to a certain API and you expect JSON , you should convert the response that you get back into JSON format.

carbon.png

Just like how fetch(URL) returns a promise, the response.json() method also returns a promise.Thus we need to resolve the promise with a .then(callback). By doing that, we will get a data by fetching from the URL.

fetch(URL)
.then(response => response.json())
.then(data => {
    console.log(data);
});

Here data variable will be the information that the API returns.This data can be of the any data types like array or number or string or object or boolean. Thus we are doing console.log(data) to find out what type of data are we getting.

Lets combine whatever we have learnt,and call this dummy API: jsonplaceholder.typicode.com/users