API for getting all kamForms data
router.get('/kam', (req, res) => {
kamForm
.find()
.then((result) => {
res.status(200).json({
kamData: result,
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
message: err,
});
});
});
And this is the API call and rendering part, when I inspect the browser all the data is showing in the console repeatedly. I will attach the ss of the console.
const PendingApplication = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios
.get('http://localhost:5000/api/kam')
.then((response) => {
console.log(response);
setData(response.data);
})
.catch((error) => {
console.log(error);
});
});
return (
<div>
<Table>
<TableBody>
{[data].map((item, index) => (
<TableRow key={index}>
<TableCell>{item.kcpname}</TableCell>
<TableCell>{item.companyname}</TableCell>
<TableCell>{item.ticketno}</TableCell>
<TableCell>{item.totalemp}</TableCell>
<TableCell>{item.kcpnid}</TableCell>
<TableCell>{item.kcpcontact}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
};
Two problems.
First, you are causing an infinite loop in your useEffect hook because there is no dependancy array provided. This will run the effect on each render (which in turn sets the state once axios resolves, causing yet another render, which runs the effect, etc).
Second, you are mapping over an array [data].map, where data is already an array of results. You should probably mean to write data.map instead.
const PendingApplication = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios
.get("https://rickandmortyapi.com/api/character")
.then((response) => {
console.log(response);
setData(response.data.results);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<div>
<table>
<tbody>
{data.map((item, index) => (
<tr key={index}>
<td>{item.name}</td>
<td>{item.status}</td>
<td>{item.species}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
useEffect(() => {
axios
.get('http://localhost:5000/api/kam')
.then((response) => {
console.log(response);
setData(response.data);
})
.catch((error) => {
console.log(error);
});
},[]);
return (
<div>
<Table>
<TableBody>
{data && data.map((item, index) => (
<TableRow key={index}>
<TableCell>{item.kcpname}</TableCell>
<TableCell>{item.companyname}</TableCell>
<TableCell>{item.ticketno}</TableCell>
<TableCell>{item.totalemp}</TableCell>
<TableCell>{item.kcpnid}</TableCell>
<TableCell>{item.kcpcontact}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
);
Use empty Square brackets like this at the end of the UseEffect. Everything will work fine. And also make sure data is not null or undefined before rendering.