skip to Main Content

i am build nextjs project and creating table from material ui and fetching data from mongoDB. how to manipulate the data from the table. i want # columns auto increment start from 1,2,3,4,5 etc. every row.

and this is my code

Data models:

{
    _id: '6609339e8891194adf3beb60'
    name: 'tuyi',
    date: '2024-03-31',
    phone: '45454',
    terapist: 'fdgdf',
    statust: 'done'
  },

page.jsx

async function getAppointment() {
  const res = await fetch("http://localhost:3000/api/appointment", {
    method: "GET",
    cache: "no-store",
  });
  // const data = await res.json();
  return res.json();
}

async function Appointment() {
  const { appointment } = await getAppointment();

  const columns = [
    { id: "_id", name: "#" },
    { id: "name", name: "Nama" },
    { id: "date", name: "Tanggal" },
    { id: "phone", name: "No Telp." },
    { id: "terapist", name: "Terapis" },
    { id: "statust", name: "Status" },
  ];

  return (

      <TableContainer>
        <Table>
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell key={column.id}>{column.name}</TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {appointment &&
              appointment.map((row, i) => {
                return (
                  <TableRow key={i}>
                    {columns &&
                      columns.map((column, i) => {
                        let value = row[column.id];
                        return <TableCell key={value}>{value}</TableCell>;
                      })}
                  </TableRow>
                );
              })}
          </TableBody>
        </Table>
      </TableContainer>
    </div>
  );
}

export default Appointment;

and turn out like this:

enter image description here

i want # columns auto increment start from 1,2,3,4,5 etc. every row.

2

Answers


  1. In MongoDB the _id will mostly be a hex string that’s monotonically increasing. However, since you only want the items to be shown with numeric ID, you can pre-process the data once you completed fetching from the API.

    In your case, you can do so after you gotten the JSON from the API:

    async function getAppointment() {
      const res = await fetch("http://localhost:3000/api/appointment", {
        method: "GET",
        cache: "no-store",
      });
      const data = await res.json();
      // Here, you can add a numerically increasing index/ID to all the items
      return data.map((row, index) => ({ ...row, index: index + 1 });
    }
    
    // After that, change the following to read from `index` key instead
    const columns = [
      { id: "index", name: "#" },
      { id: "name", name: "Nama" },
      { id: "date", name: "Tanggal" },
      { id: "phone", name: "No Telp." },
      { id: "terapist", name: "Terapis" },
      { id: "statust", name: "Status" },
    ];
    
    Login or Signup to reply.
  2. Either you can modify the data when the response is returned as @AngYC’s answer, or you can also customize the displayed value for index by column.id in the template.

    Note that you need to change the index variable from the columns array as j to avoid the variable name conflicts with i from the appointment.

    {appointment &&
      appointment.map((row, i) => {
        return (
          <TableRow key={i}>
            {columns &&
              columns.map((column, j) => {
                let value = column.id == '_id' ? i + 1 : row[column.id];
                return <TableCell key={value}>{value}</TableCell>;
              })}
          </TableRow>
        );
      })}
    

    I doubt that it is possible to create the React component with async. You will get this error: Objects are not valid as a React child (found: [object Promise]).

    So you have to work with React hooks: useState and useEffect functions as below:

    import { useState, useEffect } from 'react';
    
    export function Appointment() {
      const [appointment, setAppointment] = useState([]);
    
      useEffect(() => {
        async function fetchData() {
          setAppointment(await getAppointment());
        }
    
        fetchData();
      }, []);
    
      ...
    
    }
    

    Demo @ StackBlitz

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search