What is Fetch?

R
R.S. Chauhan
1/23/2025 4 min read

fetch is a JavaScript function used to make HTTP requests (like getting or sending data) to servers from a website or application. It is part of the modern web API, built into browsers, so you don’t need to import any libraries to use it.

Think of fetch as a way for your app to "talk" to another computer (usually a server) over the internet.

For example:

  • When you load a webpage, it might fetch data from a database to display.
  • A weather app might fetch the current weather data from an API.
  • When you submit a form, it might fetch or send that information to a server.

Why Use fetch?

  1. To Communicate With APIs: Websites or apps often use APIs to get data (like weather data, user profiles, or news articles).
  2. Efficient & Modern: fetch is simpler and more powerful than older ways like XMLHttpRequest (XHR).
  3. Promises-Based: It uses promises, which makes handling asynchronous code easier and cleaner.

How to Use fetch?

Here’s the syntax:

 

fetch(url, options)
  .then((response) => {
    // handle the response here
  })
  .catch((error) => {
    // handle errors here
  });

 

Basic Terms:

  1. url: The endpoint where you’re making the request.
  2. options (optional): An object to specify the request type (GET, POST, etc.), headers, body data, etc.

Using fetch with Different HTTP Methods

1. GET Request (Fetching Data):

This is used to retrieve data from a server.

Example:

fetch("https://api.example.com/data")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json(); // Parse the JSON response
  })
  .then((data) => {
    console.log(data); // Use the data
  })
  .catch((error) => {
    console.error("There was a problem with the fetch:", error);
  });

2. POST Request (Sending Data):

This is used to send data to a server (e.g., submitting a form).

Example:

fetch("https://api.example.com/data", {
  method: "POST", // Specify the HTTP method
  headers: {
    "Content-Type": "application/json", // Tell the server you're sending JSON
  },
  body: JSON.stringify({ name: "John", age: 30 }), // The data to send
})
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json(); // Parse the response
  })
  .then((data) => {
    console.log("Data saved:", data);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

3. PUT Request (Updating Data):

This is used to update existing data on a server.

Example:

fetch("https://api.example.com/data/1", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Updated Name", age: 35 }),
})
  .then((response) => response.json())
  .then((data) => console.log("Data updated:", data))
  .catch((error) => console.error("Error:", error));

4. DELETE Request (Deleting Data):

This is used to delete data from a server.

Example:

 
fetch("https://api.example.com/data/1", {
  method: "DELETE",
})
  .then((response) => {
    if (!response.ok) {
      throw new Error("Failed to delete");
    }
    console.log("Data deleted successfully");
  })
  .catch((error) => console.error("Error:", error));

Important Features of fetch:

  1. Promise-Based:

    • fetch returns a promise.
    • If the request succeeds, the promise is resolved.
    • If it fails, the promise is rejected.
  2. Response Object:

    • The response object contains information like status codes (200, 404, etc.) and methods to read the data (json(), text(), etc.).
  3. Error Handling:

    • If the request fails (e.g., no internet), you can catch errors using .catch.

Why Is fetch Better?

  1. Modern and Flexible:

    • It’s simpler and more powerful than older methods like XMLHttpRequest.
  2. Supports JSON Easily:

    • Since most APIs use JSON, you can parse it easily with response.json().
  3. Handles Cross-Origin Requests:

    • It works with APIs that require CORS (Cross-Origin Resource Sharing).

Example: Complete Flow

Let’s assume you have an API for a task manager. Here's how you could use fetch to:

  1. Get tasks
  2. Add a new task
  3. Delete a task
// 1. Get tasks
fetch("https://api.example.com/tasks")
  .then((response) => response.json())
  .then((tasks) => console.log("Tasks:", tasks))
  .catch((error) => console.error("Error fetching tasks:", error));
// 2. Add a new task

fetch("https://api.example.com/tasks", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "New Task", completed: false }),
})
  .then((response) => response.json())
  .then((task) => console.log("Task added:", task))
  .catch((error) => console.error("Error adding task:", error));

// 3. Delete a task
fetch("https://api.example.com/tasks/1", {
  method: "DELETE",
})
  .then((response) => {
    if (response.ok) {
      console.log("Task deleted successfully");
    } else {
      console.error("Error deleting task");
    }
  })
  .catch((error) => console.error("Error:", error));
Web DevelopmentJavaScriptprogrammingjavascriptweb development

Related Quizzes

JavaScript Variable

In JavaScript, a variable is a container that stores data values. Think of it like a box that you can put different things in. These "things" could be numbers, text, or even more complex information.

Comments (0)

No comments yet. Be the first to comment!