React Fetching Data

React Fetching Data (API Calls with Fetch/Axios)

Fetching data from APIs is an essential part of modern web applications. React provides multiple ways to make API requests, with fetch() and Axios being the most commonly used methods.

Fetching Data Using fetch()

The fetch() method is a built-in JavaScript function for making HTTP requests.

👉 Example: Fetching Data with fetch()

import React, { useState, useEffect } from ‘react’;

function FetchData() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
fetch(“https://jsonplaceholder.typicode.com/posts”)
.then((response) => {
if (!response.ok) {
throw new Error(“Network response was not ok”);
}
return response.json();
})
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error.message);
setLoading(false);
});
}, []);

if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;

return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}

export default FetchData;

📝 Explanation:

✔️ useEffect() runs once when the component mounts to fetch data.
✔️ fetch() makes an API request and returns a promise.
✔️ The response is converted to JSON and stored in state.
✔️ Errors are caught and displayed.

Fetching Data Using Axios

Axios is a popular third-party library for making HTTP requests in JavaScript.

👉 Installing Axios:

npm install axios

👉 Example: Fetching Data with Axios

import React, { useState, useEffect } from “react”;
import axios from “axios”;

function FetchDataAxios() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
axios.get(“https://jsonplaceholder.typicode.com/posts”)
.then((response) => {
setData(response.data); // Store fetched data
setLoading(false); // Set loading to false
})
.catch((error) => {
setError(error.message); // Capture error message
setLoading(false);
});
}, []); // Empty dependency array -> Runs only once

if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;

return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}

export default FetchDataAxios;

📝 Explanation:

✔️ useState([]) → Stores fetched data.
✔️ useEffect(() => {…}, []) → Runs once when the component mounts.
✔️ axios.get(url) → Fetches data from an API.
✔️ setData(response.data) → Updates state with the received data.
✔️ Handles loading and error states for a better user experience.

Why Use Axios Over Fetch?

Feature Fetch Axios
Default JSON Parsing ✅ ❌ No (Requires .json()) ✅ Yes
Error Handling ❌ Manual .ok check required ✅ Automatic error detection
Request & Response Interception ❌ Not supported ✅ Yes
Automatic Timeout ❌ No ✅ Yes

Handling POST Requests

Making a POST request allows sending data to a server.

👉 Example: Sending Data Using fetch()

This example demonstrates how to send data to an API using the fetch() method in React.

import React, { useState } from “react”;

function PostData() {
const [title, setTitle] = useState(“”);

const handleSubmit = (event) => {
event.preventDefault();

fetch(“https://jsonplaceholder.typicode.com/posts”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
},
body: JSON.stringify({ title }),
})
.then((response) => response.json()) // Convert response to JSON
.then((data) => console.log(“Success:”, data)) // Log response data
.catch((error) => console.error(“Error:”, error)); // Handle errors
};

return (
<form onSubmit={handleSubmit}>
<input
type=”text”
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder=”Enter title”
/>
<button type=”submit”>Submit</button>
</form>
);
}

export default PostData;

📝 Explanation:

✔️ useState(“”) → Manages the input field state.
✔️ handleSubmit(event) → Prevents default form submission.
✔️ fetch(url, options) → Sends a POST request.
✔️ headers: { “Content-Type”: “application/json” } → Sends JSON data.
✔️ body: JSON.stringify({ title }) → Converts state to JSON format.
✔️ Handles API response using .then() and .catch().

👉 Example: Sending Data Using Axios

This example demonstrates how to send data to an API using axios.post() in React.

import React, { useState } from “react”;
import axios from “axios”;

function PostDataAxios() {
const [title, setTitle] = useState(“”);

const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post(“https://jsonplaceholder.typicode.com/posts”, { title });
console.log(“Success:”, response.data); // Log response data
} catch (error) {
console.error(“Error:”, error); // Handle errors
}
};

return (
<form onSubmit={handleSubmit}>
<input
type=”text”
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder=”Enter title”
/>
<button type=”submit”>Submit</button>
</form>
);
}

export default PostDataAxios;

📝 Explanation:

✔️ useState(“”) → Manages input field state.
✔️ handleSubmit(event) → Prevents default form submission.
✔️ axios.post(url, { data }) → Sends a POST request.
✔️ await → Waits for the API response asynchronously.
✔️ try-catch → Handles success and errors properly.

Handling Loading and Errors Gracefully

📌 When fetching data, always:

✅ Display a loading state while waiting for a response.
✅ Handle errors gracefully to enhance user experience.

👉 Example of Centralized Error Handling

import React, { useState, useEffect } from “react”;
import axios from “axios”;

function FetchWithErrorHandling() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(“https://jsonplaceholder.typicode.com/posts”);
setData(response.data);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
};

fetchData();
}, []);

if (loading) return <p>Loading…</p>;
if (error) return <p style={{ color: “red” }}>❌ Error: {error}</p>;

return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}

export default FetchWithErrorHandling;

📝 Explanation:

✔️ useState([]) → Stores fetched data.
✔️ useState(true) → Manages the loading state.
✔️ useState(null) → Captures any errors.
✔️ useEffect() → Fetches data once when the component mounts.
✔️ .finally(() => setLoading(false)) → Ensures loading stops after fetching, whether successful or not.

Conclusion

✅ Use fetch() for a simple built-in solution, and Axios for enhanced functionality.
✅ Always handle loading states and errors properly.
✅ Use POST requests to send data to an API.
✅ Choose between fetch() and Axios based on project needs.

Course Video in English