🚀 Mastering the Fetch API in JavaScript

Shaikh AffanShaikh Affan
3 min read

Make real API calls, handle responses, and show loading like a pro!

If you’ve built anything dynamic on the web — from blogs to dashboards — you've probably needed to fetch data.
Whether it's getting user info, loading comments, or pulling stock prices, fetch() is the tool for the job.

This guide is designed for beginners and intermediate developers who want to confidently use fetch() with real-world code and good practices.


🔍 What is Fetch?

fetch() is a built-in browser method that lets you make HTTP requests (like GET, POST, etc.).
It returns a Promise — which means you’ll be using .then(), .catch(), or async/await.


🧪 Example 1: Basic Fetch (GET Request)

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

response.json() parses the body into JS
❌ Forgetting it will give you weird Response objects instead of usable data


async function getPost() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Fetch failed:", error);
  }
}

getPost();

💡 Example 2: Show Loading State in a Real App

You don't want your users staring at a blank screen. Here's a basic UI-friendly flow:

async function getUsers() {
  const loadingEl = document.getElementById("loading");
  const dataEl = document.getElementById("data");

  loadingEl.textContent = "Loading...";

  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const users = await res.json();
    loadingEl.textContent = "";
    dataEl.innerHTML = users.map((u) => `<p>${u.name}</p>`).join("");
  } catch (err) {
    loadingEl.textContent = "Something went wrong 😓";
  }
}

getUsers();

👨‍🎓 Concepts learned:

  • loading and error states

  • Parsing JSON

  • Basic DOM update after fetch


📝 Example 3: POST Request with Fetch

Sending data to an API (e.g., form submissions):

async function createPost() {
  const post = {
    title: "Hello World",
    body: "This is a new post",
    userId: 1,
  };

  const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(post),
  });

  const data = await res.json();
  console.log("Created:", data);
}

createPost();

🔒 Always send headers like "Content-Type": "application/json" when posting JSON.


❗ Common Mistakes to Avoid

MistakeFix
Not using .json()Always parse the response using await res.json()
Ignoring errors (404, 500, etc.)Check res.ok to detect bad HTTP responses
No loading/error UIAlways show feedback in the UI

🔥 Bonus: Check for HTTP Status

const res = await fetch("https://example.com/api");

if (!res.ok) {
  throw new Error("Network response was not ok");
}

🧠 Summary

TaskFetch Pattern Example
Get datafetch(url).then().catch() or async/await
Post datafetch(url, { method: "POST", ... })
Handle loadingUse flags or DOM states to indicate progress
Handle errorsUse try/catch or .catch()

✅ Final Thoughts

The fetch() API gives you full control over how your app talks to servers.
Once you master it:

  • You'll write better UIs

  • Handle APIs confidently

  • Avoid buggy or blocked states in your app

You now have the foundation — go build something great!


🔮 Coming Next:

How to Use Axios (and when it's better than Fetch)

0
Subscribe to my newsletter

Read articles from Shaikh Affan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shaikh Affan
Shaikh Affan

👋 Hey there! I’m a Frontend Developer & UI/UX Enthusiast from Mumbai, currently pursuing my BSc-IT at Kalsekar Technical Campus. I write about web development, Python, and AI, breaking down complex topics into easy-to-understand articles. My goal is to share knowledge, document my learning journey, and help others grow in tech. 🚀 Check out my latest articles and let's learn together!