I have an array of objects returned by the server which I have to display in a table. I tried using array.map() method to map the the objects as row elements into another array and then displaying that array in the JSX like <tbody>{listItems}</tbody>
const TeacherTable = () => {
let listItems
async function getTeacherData() {
const response = await fetch('http://localhost:1234/api/teacher')
const res = await response.json()
console.log(res.data)
listItems = await res.data.map(record => (
<tr>
<td>{record.teacherID}</td>
<td>{record.teacherName}</td>
<td>{record.teacherEmail}</td>
</tr>
))
}
useEffect(() => {
getTeacherData()
})
return <tbody>{listItems}</tbody>;
};
I don't know what I'm doing wrong but I doesn't seem to work. I tried to console.log() the data array to check if the data is getting passed to the frontend and its getting through without any errors but still the list doesn't get rendered.
How do I render this list of row elements from the array?
Thank you for reading this far. Hope you have a great day/night ahead.
There are a few things you should do:
listItems needs to be a state variable meaning that it causes a re-render of the component when it gets updated, because right now when listItems is set inside of getTeacherData the component isn't re-rendering. I've implemented it as state in the updated code below (called items now). If you want to read more about state and how it causes updates you should check this outuseEffect. The short explaination as to why is because you only want useEffect to be called once, for a more thorough explaination you should read this.import {useState, useEffect} from "react";
const TeacherTable = () => {
const [items, setItems] = useState([]);
useEffect(() => {
async function getTeacherData() {
const response = await fetch('http://localhost:1234/api/teacher')
const res = await response.json()
console.log(res.data)
setItems(res.data);
}
getTeacherData();
}, []);
return <tbody>{items.map(record => (
<tr>
<td>{record.teacherID}</td>
<td>{record.teacherName}</td>
<td>{record.teacherEmail}</td>
</tr>
))}</tbody>;
};