Problem:
{
"count": 2,
"rows": [
{
"id": "5ab46e31-391c-46a7-8e45-db9ada07626d",
"name": "admin",
"email": "admin@gmail.com",
"phoneNumber": "95397454542325",
"username": "admin",
"password": "$2b$10$esLfedWAPEMAgWJ5HBAFQu6u47Cbfep7hnUTDZPswb4gWFhZW0rbm",
"role": "admin",
"isActive": true,
"createdAt": "2023-09-29T11:00:55.388Z",
"updatedAt": "2023-09-29T11:00:55.388Z"
},
{
"id": "58aacbcd-2344-40f1-a9e9-11c70d44cbb4",
"name": "Aman",
"email": "aman2000@gmail.com",
"phoneNumber": "8304893218",
"username": "Aman-admin",
"password": "$2b$10$uZZrRz5bATzJ3jPCAURpKeEP/TaHhoWhmKUvWSyIrOvKMmD3yNuKi",
"role": "user",
"isActive": true,
"createdAt": "2023-10-07T09:58:51.193Z",
"updatedAt": "2023-10-07T10:00:31.590Z"
}
]
}
The above is the JSON data to be displayed
'use client'
import React from 'react';
const plans = async () => {
const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' }); // fetch gives a promise, so use const res = await
console.log(res);//table table-zebra absolute top-24 left-40
const users = await res.json();
return (
<div>
<button className='bg-sky-600 text-black p-2 rounded-lg absolute top-4 right-40 hover:text-white transition-colors'>Create plans</button>
<h1 className='absolute top-14 left-40'>Plans</h1>
<div>
<table className='table-column-group absolute top-24 left-40 min-w-full divide-y divide-gray-200 border'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.map((data) => (
<tr key={data.id}>
<td>{data.name}</td>
<td>{data.email}</td>
</tr>your text
))}
</tbody>
</table>
</div>
</div>
);
};
export default plans;
This is the front-end code in Next.js
As its nested array its not displayed i think. Maybe if changed to object. The normal arrays are displayed perfectly fine. Just this. What changes should be made in Next.js to display it correctly
Solution:
From what I can see you are getting a response from your API that consists of two keys count
and rows
, and you want to render the items within the rows
key so replace the users.map()
with users.rows.map()
;
Example
'use client'
import React from 'react';
const plans = async () => {
const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' }); // fetch gives a promise, so use const res = await
console.log(res);//table table-zebra absolute top-24 left-40
const users = await res.json();
return (
<div>
<button className='bg-sky-600 text-black p-2 rounded-lg absolute top-4 right-40 hover:text-white transition-colors'>Create plans</button>
<h1 className='absolute top-14 left-40'>Plans</h1>
<div>
<table className='table-column-group absolute top-24 left-40 min-w-full divide-y divide-gray-200 border'>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.rows.map((data) => (
<tr key={data.id}>
<td>{data.name}</td>
<td>{data.email}</td>
</tr>your text
))}
</tbody>
</table>
</div>
</div>
);
};
export default plans;