Steps to Consume an API in a React App Using Fetch
1. Use fetch() in useEffect
import { useEffect, useState } from "react";
const API_URL = "https://jsonplaceholder.typicode.com/posts";
const FetchData = () => {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
fetch(API_URL)
.then((response) => {
if (!response.ok) throw new Error("Network response was not ok");
return response.json();
})
.then((data) => setData(data))
.catch((error) => setError(error.message));
}, []);
return (
<div>
{error && <p>Error: {error}</p>}
{data.map((post) => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
};
export default FetchData;
2. Handle POST Requests
fetch(API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "New Post", body: "Post content" }),
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));