Hello friends!! this blog is about fetch() function.
I tried my best to put
my understanding into words.
It is subdivided into various parts for better understanding.
what is fetch() ?
how it is used ?
what is promise?
what is fetch()?
In fetch() we just pass the url (https) to the function
and it gives you the data from the server. fetch() used to make the
request to the server and handel the response from the server.
syntax:
var url= "https://abc.com"
fetch(url)
.then(response =>response.json())
.then(json =>console.log(json))
OR
fetch(url)
.then(function responseHandler (response){
return response.json()
})
.then(function jsonHandler(json){
return console.log(json)
})
Here, the "responseHandler","response", "jsonHandler","json"
are the function name and the parameter name .we can
name it anything but to maintain a standard we write in this form.
So to make it more convinent to read we write using the
arrow function.
how it is used?
The fetch is used to make a request to the server and handel
the response from the server.
now while we fetch you might get a bit confused in why we used
two function i.e two then.
First then ,
.then(response=> response.json())
This function takes the particular response from the server including
body, headers,status, clone, formData, constructor...etc.
what does "response.json()"do??
Convert that data in the json format and give that
data to second then.
Second then ,
.then((json)=> console.log(json))
This function takes all the data in the from of json and
prints the data in the console.
what is promise?
If i don't talk about promise it would be unfair.
promise are like the normal we use in real world.It takes the
url and give you and empty promise till when the response from
the server is not completed. After a while this promise can have
certain state.
There are three types of state in promise:
pending: This is time while request is given.
resolved: It gives particular response back
from the server.
rejected: this comes when your request is rejected
For Example
we want to fetch an api
var url ="https://abcd.com"
fetch(url)
.then(function responseHandler (response){
return response.json()
})
.then(function jsonHandler(json){
return console.log(json)
})
Here, it will fetch the data of the API i.e the
url which we have given.
It will take all the data in the json format and will
give to us.