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:
i want # columns auto increment start from 1,2,3,4,5 etc. every row.
2
Answers
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:
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 asj
to avoid the variable name conflicts withi
from theappointment
.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
anduseEffect
functions as below:Demo @ StackBlitz