What Is fetch()? A Simple Story of Getting Data from a Server
Quick Overview
The fetch() API is a modern browser web standard for making HTTP network requests to servers to send or retrieve JSON payload data.
The Real-World Story: The Express Courier Service
Think of fetch() as hiring an express courier. Your website writes down a delivery address (API Endpoint), attaches instructions (HTTP Method like GET or POST), and hands the parcel to the courier.
The courier travels across the internet highway to the backend database server, picks up the requested package, and delivers it back to your React application.
Step-by-Step Code Example
// Sending a POST request with payload data
async function createNewPost(postData) {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
});
const result = await response.json();
return result;
}