Tips on showcasing a nested array in Next.js or converting it into an object

{
    "count": 2,
    "rows": [
        {
            "id": "5ab46e31-391c-46a7-8e45-db9ada07626d",
            "name": "admin",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68090c050106280f05090104460b0705">[email protected]</a>",
            "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": "<a href='/cdn-cgi/l/email-protection' className='__cf_email__' data-cfemail='84e5e9e5eab6b4b4b4c4e3e9e5ede8aae7ebe9'>tvejsvup@qjpnzd.qjabl</a>",
            "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 JSON data should be presented

'use client'
import React from 'react';
const plans = async () => {
  const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' });
  console.log(res);

  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>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default plans;

This code is for the frontend development using Next.js. As it appears to be a nested array, there might be formatting issues in display. Consider changing it to an object structure. Regular arrays display correctly, but this particular one seems to have some trouble rendering. Possible changes needed in the Next.js codebase to ensure proper display.

Answer №1

It seems like the API response you are receiving contains two keys count and rows. If you want to display the items within the rows key, make sure to replace users.map() with users.rows.map();

For Instance

'use client'
import React from 'react';
const plans = async () => {
  const res = await fetch('http://localhost:3001/api/plans', { cache: 'no-store' }); // utilize const res = await for promises
  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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Controlling an AJAX request to fetch individuals

I am currently using an ajax request to display people data on the page, which is retrieved from a backend database. The search form on the page includes options for location, sector, service, and job title. Below is the javascript code being used: //var ...

Controlling dynamic fields within a web page - Utilizing Postgres and MongoDB databases

My application utilizes MongoDB and PostgreSQL as databases, with AngularJS for the UI. A key requirement is the ability to dynamically add fields (columns) on pages, allowing users to define their attributes when adding these fields to the system. In add ...

Tips for achieving comma-separated user input via ngModel and appending it to an array

I am working on an email template that includes a cc option. I want users to be able to add email addresses with commas separating them and then push them to an array called $scope.notifyCtrl.cc. How can I accomplish this using AngularJS 1.5 and above? mai ...

Avoid wrapping elements

Is there a foolproof method or best practice to prevent an HTMLElement from wrapping? Specifically, I'm referring to elements with relative positioning. One possible solution could be using absolute elements and adjusting their left position based on ...

Passing data from the controller to the $resource object in Angular with the MEAN stack

After several attempts to troubleshoot my issue with passing parameters to the Express server, it turns out the problem lies on the Angular side. When I manually inserted the id in the flConstruct.js function, the query worked correctly. It appears that ...

Error encountered during the Vercel build process for Next.js (Digest: 251669207)

Upon completion of the build process in Vercel, I encountered a white screen displaying the following message: Application error: a client-side exception has occurred (check the browser console for more information). Digest: 251669207 The console output ...

Encountered a difficulty in resolving the dependency flawlessly within the Next.js application

Every time I try to deploy my next.js project, I encounter the same error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

Getting data from a PHP request using AngularJS can be achieved by creating an HTTP request in

I am trying to send a basic REST service request using Angular for the PHP code below. Unfortunately, the request is resulting in an error. Check out the live code here PHP Code <?php /* Simple array */ $json = array("status" => 0, "msg" => ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

What is the process to obtain the child theme URL in WordPress?

Currently, I am working on creating a child theme for my WordPress website. I have successfully uploaded the assets folder which contains both CSS and JavaScript files. This child theme will be completely customized to suit my needs. Within the <head&g ...

Processing lines with numerical values retrieved from a file and storing them in an array using bash

I've been working on a script that extracts the 4th column of a file and stores it in an array for comparison. The goal is to increment a counter if the elements fall between 0 and 500. However, despite running the script multiple times, the counter a ...

What is a way to leverage the array or object data within the method object in order to reference the specific link in VUEJS?

How do I utilize the "LINK" property in the methods object? You might be able to infer my intentions, but just in case, here's what I'm aiming for: In Vue.js, I am attempting to extract all the data from the Data method's object so that I ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

Guide to adding a JS file from npm package to a new page in Nuxt.js

I am facing an issue where I have multiple npm packages containing client-side scripts that I need to include in different pages of my Nuxt.js project. I attempted to achieve this by using the following method: <script> export default { head: { ...

Unforeseen outcomes arise when toggling expansion in JavaScript

I have a pop-out div at the top of my page that expands and closes on toggle. Also, when I toggle the pop-out div, it changes the top position of another div (a side pop-out menu). The issue is that the side pop-out menu should only appear when clicking ...

Update the status value if the date is earlier than the current date

Within my table, there is a status field and expiration date. I need to update the status value in the database when the expiration date is before the current date. One option could be to implement a scheduled task. Are there any alternative approaches to ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

Modification of window size using jQuery animations

Currently, I am working on creating a sidebar that slides in from the left side of the screen. To achieve this effect, I have set the menu element to float left with a width of 40% and a margin-left of -40%. However, when I try to reveal the sidebar by sw ...