javascript

How to Use Fetch API in Javascript

In this tutorial, we are going to use the Fetch API to fetch all public holidays in the United States.

We’ve have written extensively on the Fetch API here.

So, let’s begin.

  getUsHolidays = async () => {
   const url = "https://date.nager.at/api/v2/publicholidays/2020/US";
    const obj = {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    };
    await fetch(`${url}`, obj)
      .then((response) => response.json())
      .then((responseJson) => {
        console.warn(responseJson);

      })
      .catch((error) => {
      console.error(error.message);
      });
  }

Explanation:

Here, we’re using async/await with GET request method, and the content type is application/json.

We’re getting the response on the console and we’re also catching errors as well because, should the request not go through, we want to know what happened.

Result:

Fetch API in Javascript

Conclusion:

Here’s how we can make a simple GET request using Fetch API in Javascript. Let me know what you think in the comments.

check out the official documentaton here

Recent Posts

UI/UX Design — Explained Like You’re 5

Download the Codeflare iOS app and learn on the Go 1. What UI and UX…

1 day ago

Costly Linux Mistakes Beginners Make

1. Running Everything as Root One of the biggest beginner errors. Many new users log…

4 weeks ago

How Keyloggers Work

A keylogger is a type of surveillance software or hardware that records every keystroke made…

1 month ago

JavaScript Memoization

In JavaScript, it’s commonly used for: Recursive functions (like Fibonacci) Heavy calculations Repeated API/data processing…

2 months ago

CSS Container Queries: Responsive Design That Actually Makes Sense

For years, responsive design has depended almost entirely on media queries. We ask questions like: “If…

2 months ago

Cron Jobs & Task Scheduling

1. What is Task Scheduling? Task scheduling is the process of automatically running commands, scripts,…

2 months ago