What is Fetch?
Fetch method provides an interface to access and manipulate resources across the web.
A basic fetch is very simple since you only require the URL to the resource you want to get data from.
Example
fetch("https://fakestoreapi.com/products")
The fetch method returns a promise which brings us to the question,
What is a promise?
A promise is an assurance that the request is being processed and you will soon receive a response. After the fetch request is complete the promise is resolved with the response object.
A JavaScript promise object can be:
Pending
Fulfilled
Rejected
The promise object supports two states: State and Result.
This can be demonstrated like so;
Promise.state Promise.result
"Pending" undefined
"Fulfilled" a result value
"Rejected" an error object
Reading the response
After the fetch() is complete an object is given back as a response. The object can be read in a couple of ways:json,text.
You chain the .then method to tell JavaScript that after completing the request convert the response object into a certain format.
Example
fetch("url")
.then(response =>response.json())
.then(data => console.log(data))
Status code of the response
The response object gives a status code of 200 and a status text of ok when a request is successful and 404 when an error was an error was encountered or if the requested resource doesn't exist.
Example
function fetchText() {
fetch("url")
.then(response => console.log(response.status) // 200
if (response.status === 200) {
.then(response => response.json)
}
}
fetchText();
There are other types of status codes:
500-occurs when requested url throws a server error.
300-309-occurs when requested url is redirected to a new page with the response.
The normal behaviour is GET we can override this by adding an object to the fetch object like so;
fetch("url",object)
inside the object is where certain properties are defined
The properties
Method
The request method eg GET,POST,PATCH,DELETE.
Headers
When you want to add headers to your request.
It is contained within headers object.
Example
Content-Type and Accept-specifies content types of request body and output. Can be application/json for json files.
Range-controls the pagination in list of API calls
Compression.used to compress the data in a response,it is done by setting the Accept-Encoding header
Body
Here is where we pass whatever we want to send in an object format and then use the JSON.stringify method to convert the object to a string format so that the object can be sent across the web. When the content in the body arrives at the passed in url it is converted back to an object
Catch
We add a function called a catch(). This allows us to write code to "handle" the error when something goes wrong in a fetch() request.
Example
const name = { username: 'example' };
//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(name),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
console.error('Error:', error);
});
Top comments (2)
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎thanks for the feedback