The Fetch API provides an interface for fetching resources similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises which make working with request and response easier, avoiding the callback hell.
The Fetch API provides
fetch() method defined on
window object which can be used to make network request.
Let’s see it in action!
We will start with minimal markup required for this demo
The button having
fetchdata when clicked, will fetch data from URL
https://api.github.com/users/gulshansainis and display the result in
<div id="result"></div>. The URL we are using is the public URL of my GitHub profile. If you open the above URL directly in the browser you should see the JSON result that we expect form fetch API.
Next, we can create an event listener for button having id
fetchdata, so that when it is clicked the listener
Let me walk through the above code line by line
const fetchDataBtn = document.querySelector("#fetchdata");- handler for fetch button
const result = document.querySelector("#result");- handler for result div
result.innerText = "Loading....";
fetch("https://api.github.com/users/gulshansainis"). When this piece of code is executed, browser immediately returns a Promise object. A Promise could be in
pendingi.e. initial state,
fulfilledi.e. success, and
fulfilledstate it returns a
Responseobject. Within the first
then()we can call this json method to return the response body as JSON i.e.
then((res) => res.json())
res.json()again return a Promise so we need to again call the
then()method we are setting the
datarecieved from API inside the result div i.e.
result.innerText = JSON.stringify(data, null, 2);. Since, it return a JSON object I have used the
JSON.stringify(...)to pretty print result on screen.
fetchDataBtnlistener that will listen for
clickevents and make a Fetch API request.
A working demo of code discussed above
A more cleaner approach would be to use Fetch API with Async/ Await. Replacing the
then() chain with Async/ Await will make code more cleaner and easier to read.
Tip: We should wrap `await` calls in try/catch block to handle any error that might be caused due to wrong resource URL, server error or network error.
Remember - The
await keyword only works in