fetch()allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
If we run that we can see on the console that it’s returning a Promise.
Since fetch() is promise based, you can use async-await or .then() and .catch() to fetch the data also. Now, we’re using .then() method to get the response object as follows
which will return our response object as below.
So, you can see that we’re getting a response with a status code of (200) “OK”. That means the request has succeeded. The body contains all of our data. But we can’t read the data right now. First we’ve to covert this to a JSON object using .json() method. This will return another promise so, we’ve to use another .then() method and pass the data into it.
And then we can see in our console panel our data like below.
Like that we can easily get out data using fetch api.
ERROR Handling in Fetch()
To handle the error we use .catch() method to get the error message out with a error status code.
Modifying Data Using Fetch()
Since now we are getting the data as a response. What if we wanted to modify our data? To do that we need “POST” or “PUT” request to create or replace data. To use this type of request we have to pass the method as a second argument in the fetch() method. As the third argument we’ve to enter the Headers object. Inside the headers object we’ve to enter the ‘content-type’
Headersinterface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.
And then we have to write the data we want to create or modify as the next argument . But this will generate an error. Because the data we get as a JSON object, to sync the data correctly with the json object we’ve to use json.stringify() to convert it into a string.
In the above code I created a POST request to create a name of “Sankalan” using fetch() method which gives the below response:
Here you can see youre getting a user with that specified name into the data.
In this way you can use fetch API to get the data or modify, create , delete the data using fetch() method. Here is some more resources to learn: