DEV Community

Uigla
Uigla

Posted on

Vanilla JavaScript data fetch

VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery.

Why should I know Vanilla javascript basics?

In every app development, there comes a day when something doesn't work as expected, and you don't know why. That's when you have to start digging. When you begin searching through poorly documented, complex, generic, pure JavaScript code, you'll need a deep understanding of JS to make it. Otherwise, I can guarantee you're going to lose all the precious time you saved by using your fancy framework.

Knowing vanilla JavaScript will make you actually understand JS frameworks and help you choose the right one when you need it.

This guide shows you how to build and run a simple Vanilla.js app. Using fetch (built-in asyncronous method) to reach data and print it.

App is divided in three files:
index.html, index.css and index.js (vanilla js)

First, in our html, reference in "head" our index.css and inside "body" our index.js, like this:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>

<body>
    <section class="blog">
        <div class="container">
            <h1>Blog</h1>
            <div id="blog" class="w-block"></div>
        </div>
    </section>
    <script src="./index.js" type="text/javascript"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

You will need a server to run the code, if you're usin VScode, you can use Live server

index.css

body {
  background-color: #f2f2f2;
}
h1 {
  text-align: center;
}
h1,
h2 {
  color: #d98e04;
}
a {
  display: block;
  margin-top: 30px;
  color: #f2b705;
}
.w-block {
  display: block;
  max-width: 550px;
  margin: 5rem auto;
  line-height: 1.5rem;
}
.w-block .university-feed {
  list-style-type: none !important;
}
.w-block .university-feed li a {
  text-decoration: none;
  transition: all 250ms;
}
.w-block .university-feed li a:hover {
  color: #2563eb;
}
.w-block h2 {
  margin: 1rem 0;
}
.w-link {
  margin: 1.5rem 0;
}
.w-link a {
  margin: 0 1rem 0 0;
  display: inline;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

index.js (Vanilla JavaScript)

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node.

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.

The forEach() (is a built-in array method) executes a provided function once for each array element.

// DOM element where are adding more Nodes with extracted data
const universitiesList = document.querySelector("#university");

// Check url - http://universities.hipolabs.com/search?country=United+Kingdom
// We have splitted in variables in case we want to change the url that supports different routes (get APIs)
const country = "United+Kingdom";
const api = "http://universities.hipolabs.com/search?country=";

/*  Helper functions */
// Create elements
function createNode(element) {
  return document.createElement(element);
}
// function append element
function append(parent, child) {
  return parent.appendChild(child);
}
// Adding "ul" Node element
const ul = createNode("ul");
ul.classList.add("university-feed");
// build url
function buildURL() {
  return `${api}${country}`;
}
// @parameter _amount defines how many universities we want to show
//  if you don't pass the "_amount" parameter into the function, its parameters will have the default values of 6
const showUniversities = (_amount = 6) => {
  fetch(buildURL())
    .then((response) => response.json())
    .then((universities) => {
      // inside "universities" array, we've 100 objects and all of them has same properties: country, name, web_pages (and few more)
      // We're cutting json array to first "_amount" objects
      universities.length = _amount;
      console.log(universities[0] /* json[0].web_pages */);

      universities.forEach((university) => {
        // creating node elements
        let li = createNode("li"),
          a = createNode("a"),
          h2 = createNode("h2"),
          hr = createNode("hr");

        // specifying value, attributes and className
        h2.innerText = university.name;
        a.innerText = university.web_pages[0];
        a.target = "_blank";
        a.rel = "noreferrer";
        a.href = university.web_pages[0];
        //appending
        // append(li, h4);
        append(li, h2);
        append(h2, a);
        append(ul, li);
        append(ul, hr);
      });
      // appending to university university to feed
      append(universitiesList, ul);
    }).catch(function (error) {
      console.log("Error during fetch: " + error.message);
    });
};

showUniversities();

Enter fullscreen mode Exit fullscreen mode

I hope it has been helpful.

Top comments (1)

Collapse
 
gruwt profile image
gruwt

Thanks mate, very useful simple code