Skip to content

Data Fetching

The fetch() method is built into modern browsers.
It allows making HTTP requests to retrieve or send data to an API.

It returns a Promise, making it asynchronous: the code continues running while the request is in progress.


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

With async/await, the code is more readable:

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

You can also send data with fetch.
You need to specify the method (POST, PUT, DELETE) and often include headers.

async function createPost() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "New Post",
body: "Post content",
userId: 1
})
});
let data = await response.json();
console.log("Created:", data);
} catch (e) {
console.error("Error:", e);
}
}
createPost();

  • GET → read data
  • POST → create data
  • PUT → update data
  • DELETE → delete data

⚠️ Note: fetch does not throw on HTTP 404 or 500 by default.
You must manually check response.ok and response.status.

let response = await fetch("https://jsonplaceholder.typicode.com/404");
if (!response.ok) {
console.error("HTTP Error:", response.status);
}

  • fetch always returns a Promise.
  • response.json() converts the response to a JavaScript object.
  • You must handle errors with try/catch or .catch().
  • fetch does not throw on HTTP 404 or 500 → check response.ok.

  • Always verify response.ok before processing the response.
  • Handle errors with try/catch (if using async/await) or .catch() (if using Promises).
  • Properly use headers (Content-Type, Authorization for tokens, etc.).
  • Prefer async/await for readable and maintainable code.