Rendering a list of row elements in react

I’m back again with another problem I’m stuck with in my project.

I’m using React to create the user interface, express to create the server and api and firestore from Firebase as my database. So far so good. I’m able to send form data from frontend to server and then to database and also get data from database to server and then send it to frontend. So the sandwich is working fine. I am using fetch API to post data and also get data from the server.

I’m making a get request to the server to get all the data about the teachers from the database and its responding properly with the correct data without any errors. In the frontend, I used async await to get the data and its something like this

 async function getTeacherData() {
    const response = await fetch('http://localhost:1234/api/teacher')
    const res = await response.json()
}

So it returns an object that has two properties a response message( res.message ) and the teacher’s data ( res.data ). The res.data is an array of objects that has several properties like teacherID, teacherEmail, teacherName.

I want to render these properties in a table. I tried to map each object of the data array as a row into another array and display that array but it doesn’t show anything. I don’t know how to render a list of html elements in the frontend from the array of objects

Hello!

Could you paste all the code involved? For starters, the code you used to create the table but didn’t work :slight_smile:.

1 Like

I agree with skaparate - it will be a lot easier to help you if we can see what we are working with.

In general, React is very good at handling arrays. If you have an array of elements, then you can just put that in your JSX:

<div>
  { myArrayOfReactElements }
</div>

If you have an array of data, you can map over it…

<div>
  { myData.map(/* ...  */) }
</div>

and as long as that returns an array of elements, you’re golden.

The latter is a very common pattern. You can see a lesson about it here.

1 Like

Here’s the entire code for the table component

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 with this

What error are you getting?

Among other things, I would make listItems a state variable, so the component will know to rerender. I would also probably just have that be an array of objects and have a separate function turn it into an array of JSX, but that is more preference.

2 Likes

There’s no error shown in the console. The data is also returned successfully by the server. When I console.log() the response from the server, the data is present inside the response object. I tried mapping it to another array but still the JSX elements are not being displayed. Also I tried to create the array as a state variable but there are a lot of re renders when I console.log the state array.

I thought this might not be good so I deleted it and tried something else. But when I create the array as a state variable the JSX gets displayed

Will it be ok to have the array as a state variable?

I think I’ve reached the limit of how much I can help you without seeing the code. I think I need either a repo or an online IDE where you have this.

I would suggest you separate out the map from the fetch function and give the useEffect an empty dependencies array.

Example code using jsonplaceholder for the data.
import { useEffect, useState } from "react";

export default function App() {
  const [teachers, setTeachers] = useState([]);

  async function getTeacherData() {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const teachers = await response.json();
    setTeachers(teachers);
  }

  useEffect(() => {
    getTeacherData();
  }, []);

  return (
    <table className="App">
      <tbody>
        {teachers && teachers.map((teacher) => (
          <tr key={teacher.id}>
            <td>{teacher.id}</td>
            <td>{teacher.name}</td>
            <td>{teacher.email}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
3 Likes