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

Leveraging the power of context to fetch data from a store in a React component within the Next

I'm having trouble with the title in my React project, and I'm new to React and Nextjs. When trying to fetch data from my dummy chat messages, I encountered this error: × TypeError: undefined is not iterable (cannot read property Symbol(Sy ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...

How can one effectively manage asynchronous behavior on the client side of a Meteor application?

My focus is on Meteor. I want to connect with the Facebook API through Meteor's HTTP in order to show images on Meteor's client side. I've come across suggestions like Fiber Futures, storing data in Sessions, and triggering a synchronous se ...

Encoding identification data from JSON using ColdFusion

Hello everyone, I've been puzzling over how to intercept and encrypt database record ID from a JSON request in ColdFusion. Below is the code I have so far, along with my unsuccessful attempt. Any assistance would be greatly appreciated. <cfquery ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

Combining two or more arrays containing similar values into a single array

Within my array, there are 100 subarrays, each containing 3160 values of an object with two attributes: a sequence number (which only appears if it is present as 1), and another value of either 0 or 1. My goal is to merge all 100 arrays into one single ar ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Convert your Express.js API routes to Next.js API routes for better performance and flexibility

I'm currently working on an Express API route that looks like this: const router = require("express").Router(); router.get("/:jobId/:format", async (req, res) => { try { const { jobId, format } = req.params; if (form ...

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

Having trouble deleting element despite having the correct ID?

Whenever I click on the map, it adds an element to the map div using this line of code: $('#map').append('<label>test:</label><input type="hidden" name="map_coords" id="' + e.latlng.lat + '" value="' + e.latlng ...

Using third-party libraries like jQuery, CSS, and JavaScript in your React project by directly importing them into the index.html file can be a more efficient approach compared

When working with React, is it advisable to import external JavaScript, jQuery, and CSS files into the index.html file in the public folder? Are there any potential performance implications associated with this practice? I have utilized some jQuery functi ...

a guide on expanding a submenu in a shiny dashboard sidebar without using automated functions

I am facing a challenge in manually expanding a submenu within a sidebar on shiny dashboard. The function updateTabItems does not seem to work with nested menus, only with normal menus. For example, when I click on 'Switch tab', it switches the ...

Switching from React version 15.6.2 to 16 results in disruptions to the functionality of the web

Currently, I am encountering an issue where none of my index.js files are rendering. After using the react-scripts to build my web application in version 16.2.0, I receive an error stating that r.PropTypes is undefined when trying to access the localhost a ...

Ways to analyze three PHP arrays and organize outcomes that are not duplicated into separate new arrays

I have an array containing three nested arrays. $rubros array(3) { [1]=> array(8) { [0]=> array(1) { ["idRubro"]=> string(1) "1" } [1]=> array(1) { ["idRubro"]=> str ...