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;
No comments:
Post a Comment