Data Fetching
What is fetch?
Section titled “What is fetch?”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.
Simple Example (GET)
Section titled “Simple Example (GET)”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
Section titled “With async/await”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();Sending Data (POST)
Section titled “Sending Data (POST)”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();Other HTTP Methods
Section titled “Other HTTP Methods”- GET → read data
- POST → create data
- PUT → update data
- DELETE → delete data
Checking HTTP Errors
Section titled “Checking HTTP Errors”⚠️ 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);}Key Points
Section titled “Key Points”fetchalways returns a Promise.response.json()converts the response to a JavaScript object.- You must handle errors with
try/catchor.catch(). fetchdoes not throw on HTTP 404 or 500 → checkresponse.ok.
Best Practices
Section titled “Best Practices”- Always verify
response.okbefore processing the response. - Handle errors with
try/catch(if using async/await) or.catch()(if using Promises). - Properly use headers (
Content-Type,Authorizationfor tokens, etc.). - Prefer async/await for readable and maintainable code.