Fetch API provides you a way to easily access and modify the data from an remote API. It has gained significant importance in the wake of recent advancements in the field of APIs.
Fetch API
differs from XMLHttpRequest in the sense that the former is a promise based and
allows to more requests to the web server. It is also clean and easy to
understand.
It provides
a global fetch() method and only takes a simple url of the destination site
from which you have to fetch the data.
Lets try
some code!
The basic
syntax of Fetch API:
fetch(url)
.then(function() {
// handle the response
})
.catch(function() {
// handle the error
});
Here url is
the URL of the API from where you have to fetch the data. Fetch returns a
promise and if the condition is true then the function within the .then()
method is executed. If we encounter any error then we handle that in the .catch
method.
Lets see
this how it works through an example!
Fetching
data from an API using Fetch()
const url = const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then((res)=>{
return response.json();
}).then((dat) =>{
Console.log(dat);
});
Lets
understand the above code. First we define a url variable that holds the url
from which we have to fetch the data. Then fetch() methods fetches the data
from the url and since fetch() returns a promise we handle the res object that
we receive in response in the .then() method. The response is an object
containing many functions and properties that we can use but we need that data
in the json format. So we convert that res object in json format using
response.json() method and return the object. Here we have to again use another
.then () method to use the json data and hence we create another .then() method
taking argument in the form of dat and displaying it on console.
So that’s
it. The fetch() method is simple and easy to use. In the next blog post we will
see advanced implementation of the fetch() method and see how we can take data
from url and display the data in an html format.
Till then, Happy
Coding!
0 Comments