Javascript Fetch API

Sending a Request

let response = fetch(url);
fetch(url)     
.then(response => {
// handle the response
})
.catch(error => {
// handle the error
});

Reading the Response

fetch('/readme.txt')     
.then(response => response.text())
.then(data => console.log(data));
async function fetchText() {     
let response = await fetch('/readme.txt');
let data = await response.text();
console.log(data); }

Handling the status codes of the Response

async function fetchText() {     
let response = await fetch('/readme.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK

if (response.status === 200) {
let data = await response.text();
// handle data
}
}
fetchText();
200 
OK
let response = await fetch('/non-existence.txt');  
console.log(response.status); // 400
console.log(response.statusText); // OK
400
Not Found

JavaScript Fetch API example

[{         
"username": "john",
"firstName": "John",
"lastName": "Doe",
"gender": "Male",
"profileURL": "img/male.png",
"email": "john.doe@example.com"
},
{
"username": "jane",
"firstName": "Jane",
"lastName": "Doe",
"gender": "Female",
"profileURL": "img/female.png",
"email": "jane.doe@example.com"
}
]
<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Demo</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container"></div>
<script src="js/app.js"></script>
</body>
</html>
async function getUsers() {
let url = 'users.json';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
async function renderUsers() {
let users = await getUsers();
let html = '';
users.forEach(user => {
let htmlSegment = `<div class="user">
<img src="${user.profileURL}" >
<h2>${user.firstName} ${user.lastName}</h2>
<div class="email"><a href="email:${user.email}">${user.email}</a></div>
</div>`;

html += htmlSegment;
});
let container = document.querySelector('.container');
container.innerHTML = html;
}
renderUsers();

In Summary

  • The Fetch API allows you to asynchronously request for a resource.
  • Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json(). These methods resolve into the actual data.
  • Use the status and statusText properties of the Response object to get the status and status text of the response.
  • use the catch() method or try...catch statement to handle a failure request.

--

--

--

just a junior developer navigating through problems in Rails and React. I like sharing my solutions, thinking processes and sometimes frustration..

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

About the suspension of some functions

ReasonML for JS developers

Publish npm package into Nexus and use it in another app

Issues that you may face when working with Next.js the first time

Native vs React Native ( Android and IOS ) Which one is better?

Angular NGX-Translate Lazy Loaded Modules

JavaScript — Variables, Template Literals, For&While Loops

FLEXing our CSS skills

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Saman Batool

Saman Batool

just a junior developer navigating through problems in Rails and React. I like sharing my solutions, thinking processes and sometimes frustration..

More from Medium

Which JS Framework Your Project Requires: Angular vs. React 2022

The concept of Closure in JavaScript

Intro to Programming using Javascript

Learn JavaScript Testing