Introduction

The fetch() method in javascript is used to request data from the server. Any sort of API that returns data in JSON or XML can be requested. The URL to request is the only parameter needed for the fetch() method, which also returns a promise. fetch() method is  available in the global scope that instructs the web browsers to send a request to a URL.

When fresh data is required, JavaScript has the ability to load it from the server via network requests.

We could, for instance, utilise a network request to:

Send an order, load user data, get the most recent updates from the server, etc

Without having to reload the website, too!

AJAX, which stands for "Asynchronous JavaScript And XML," is a catch-all word for network queries made by JavaScript. However, we don't have to use XML; that word is there because the phrase dates back to a previous era. That phrase may be one you've already heard.

Sending a network request and requesting information from the server can be done in a variety of ways.

We'll start with the fetch() method because it is up to date and functional. Although it can be polyfilled, older browsers do not support it, but current ones do.

Syntax:

fetch('url')           //api for the get request

  .then(response => response.json())

  .then(data => console.log(data));

  .catch(error => {
        // handle the error
    });


Parameters: This method requires one parameter and accepts two parameters:

URL: It is the URL to which the request is to be made.

Options: It is an array of properties. It is an optional parameter.

The fetch() method returns a Promise so you can use the then() and catch() methods to handle it.

The resource is accessible once the request has been fulfilled. The promise will now turn into an object called a Response.

The API wrapper for the fetched resource is the Response object. There are several helpful features and methods to inspect the response in the Response object.

Steps involved in fetch() method:

Example:

JSON File:

[{
    "username": "Board Infinity",
    "firstName": "Board",
    "lastName": "Infinity",
    "gender": "Male",
    "email": "boardinfinity@example.com"
},
{
    "username": "Devi",
    "firstName": "Kode",
    "lastName": "Devi",
    "gender": "Female",
    "email": "kode.devi@example.com"
}
]

Html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch() Method</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container"></div>
    <script src="apps.js"></script>
</body>
</html>

Apps.js:

fetch() method is used to get the user data and render the data inside the <div> element with the class container

async function getUsers() {
    let url = 'details.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">
                            <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();


write your code here: Coding Playground

Conclusion

The Fetch API allows you to asynchronously request for a resource.The explanation and demo were given in this article.Although not currently supported by all browsers, the Fetch API is a great substitute for XMLHttpRequest.