In React applications, handling data and fetching data from APIs are common tasks. Let's explore different methods and techniques for data handling and API fetching.
You can use the Fetch API to make GET requests and fetch data from an API endpoint:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Data fetching in React can be synchronous or asynchronous. Synchronous data fetching blocks the main thread until data is fetched, while asynchronous data fetching allows the main thread to continue executing other tasks while fetching data in the background.
Synchronous data fetching is straightforward with the Fetch API. You make a request and handle the response synchronously:
import React, { useState, useEffect } from "react";
const SyncDataFetching = () => {
const [data, setdata] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((json) => setdata(json));
}, []);
return (
<>
{data.map((val, index) => {
return (
<p key={index} style={{ textAlign: "left" }}>
{index + 1} - {val.name} {val.title}
</p>
);
})}
</>
);
};
export default SyncDataFetching;
Asynchronous data fetching is a more modern approach that allows the main thread to continue running while data is fetched in the background. This prevents UI blocking and improves user experience:
import React, { useState } from "react";
const AsyncDataFetching = () => {
const [data, setData] = useState(null);
const fetchData = async () => {
// Asynchronous data fetching
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
const jsonData = await response.json();
setData(jsonData);
};
return (
<>
<button onClick={fetchData}>Fetch Data (Async)</button>
{data && (
<div>
<h2>{data.title}</h2>
<p>{data.body}</p>
</div>
)}
</>
);
};
export default AsyncDataFetching;
In web development, different HTTP request types are used to perform various actions on the server, such as retrieving, creating, updating, and deleting data.
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error fetching data:", error));
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify({
title: "New Post",
body: "This is a new post.",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error creating post:", error));
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "PUT", // or 'PATCH'
body: JSON.stringify({
id: 1,
title: "Updated Post",
body: "This post has been updated.",
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error updating post:", error));
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => {
if (!response.ok) {
throw new Error("Failed to delete post");
}
console.log("Post deleted successfully");
})
.catch((error) => console.error("Error deleting post:", error));
Different HTTP request types are used for various CRUD operations: GET for retrieving data, POST for creating data, PUT/PATCH for updating data, and DELETE for deleting data.
Objective: Create a component that fetches user data from the GitHub API and displays it.
Create a FetchUsers Component:
Create a new file FetchUsers.jsx
and define a component that fetches user data from the GitHub API.
// FetchUsers.jsx
import React, { useState, useEffect } from "react";
const FetchUsers = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://api.github.com/users")
.then((response) => response.json())
.then((data) => setUsers(data))
.catch((error) => console.error("Error fetching users:", error));
}, []);
return (
<div>
<h2>GitHub Users</h2>
<ul>
{users.map((user) => (
<li key={user.id}>{user.login}</li>
))}
</ul>
</div>
);
};
export default FetchUsers;
Use the FetchUsers Component:
Import and use the FetchUsers
component in your App
component to see the list of GitHub users.
// App.jsx
import React from 'react';
import FetchUsers from './FetchUsers';
const App = () => {
return (
<div>
<h1>GitHub Users</>
<FetchUsers />
</div>
);
};
export default App;
This task will help you practice fetching data from an API and displaying it in a React component. You can explore more features and endpoints of the GitHub API to enhance your understanding of data fetching in React.