Skip to content

fetch api

The fetch API provides an interface for fetching (sending/receiving) resources. It uses Request and Response objects . The fetch() method is used to fetch a resource (data).

js
let promise = fetch(url, [option]);

we can use promise chaining to retrive the DataTransfer.But as we learned a better way async/await ,we will use that

js
const URL = "https://emojihub.yurace.pro/api/all";
const getEmoji = async () => {
  let response = await fetch(URL);
  console.log(response);
};
getEmoji();

we will get the response like this (image(scrnshot))

The response we are getting is in JSON format.We have to convert it into JS Object.

Understanding terms:

  • AJAX: Asynchronous JavaScript and XML
  • JSON: JavaScript Object Notation
  • json() method:
    • Returns a second Promise that resolves with the result of parsing the response body text as JSON.
    • Input: JSON
    • Output: JavaScript Object
js
const l = document.querySelector("#emoji");
const URL = "https://emojihub.yurace.pro/api/all";
const getEmoji = async () => {
  let response = await fetch(URL);
  console.log(response);
  let data = await response.json();
  console.log(data[6].htmlCode);
  l.innerHTML = data[98].htmlCode[0];
};
getEmoji();

we can call the fetch api using the promise chaining also-

js
const l = document.querySelector("#emoji");
const URL = "https://emojihub.yurace.pro/api/all";
function getEmoji() {
  fetch(URL)
    .then((resonse) => {
      return resonse.json();
    })
    .then((data) => {
      console.log(data[6].htmlCode);
      l.innerHTML = data[98].htmlCode[0];
    });
}
getEmoji();

To understand fetch api call ,here is a mini project

Project Image

Currency Converter

A currency converter for learning Fetch API calls, enabling real-time currency conversion.