Fetch List of Employees in React
List of Employees present at some URI i.e http://127.0.0.1:9091/employee/fetch
[{"id": 1001,"name": "Dinesh","salary": 10000.0},{"id": 1002,"name": "Kumar","salary": 10000.0},{"id": 1003,"name": "Dinesh","salary": 10000.0},{"id": 1004,"name": "Kumar","salary": 10000.0}]
React Output:
| 1001 | Dinesh | 10000 |
| 1002 | Kumar | 10000 |
| 1003 | Dinesh | 10000 |
| 1004 | Kumar | 10000 |
React Code to Fetch this Data:
import React, { useState, useEffect } from "react";
import UserService from "../services/user.service";
const Employee1 = () => {
const APIURL = "http://127.0.0.1:9091/employee/fetch";
const empployee = {
id: 10013,
name: "Dinesh",
salary: 10000.0
}
const [emp, setEmp] = useState([empployee]);
useEffect(() => {
fetchEmployees();
}, []); // << super important array
const fetchEmployees = () => {
fetch(
`${APIURL}`
).then((response) => response.json())
.then(
(data) => setEmp(data)
);
}
return (
<div className="container">
<table>
{emp.map((emp) => (
<tr>
<td>{emp.id}</td>
<td>{emp.name}</td>
<td>{emp.salary}</td>
</tr>
))
}
</table>
</div>
);
};
export default Employee1;
Fetching employee records from a REST API and displaying them in a React table is a practical example of integrating frontend applications with backend services. Using useState to manage employee data and useEffect to fetch records when the component mounts demonstrates how React hooks simplify data fetching and state management. Adding proper error handling, loading indicators, and unique keys when rendering table rows can make the implementation more reliable.
ReplyDeleteDevelopers learning to build dynamic web interfaces can benefit from understanding React components, hooks, API integration, and state management. The ReactJS Course is relevant for learners who want to develop interactive user interfaces and connect them with backend APIs.
The same API integration concepts are also useful when developing mobile applications that need to retrieve and display data from server-side services. React Native allows developers to apply their JavaScript and React knowledge to mobile app development while building applications for different platforms. The React Native Course is relevant for those interested in extending their frontend development skills to mobile applications.
ReplyDelete