skip to Main Content

I am working on a MERN project that requires to fetch assets from database. The data is appearing in console but the same is not getting rendered into the table.There is no error on warning.image of the output with console

Below are my react component and server code. I have attached database screenshot.[Database image] (https://phpout.com/wp-content/uploads/2023/05/9oneK.jpg)

import {React,useEffect, useState} from 'react';
import NavBar from '../Shared/Navbar';
import axios from 'axios'


function AssetList() {
                              
const [asset,setAsset] = useState([])

   const getAssets = ()=>  {
          
                 axios.get('http://localhost:6001/assets/get-assets')
                  .then((res)=>{
                      setAsset([res.data])
                      console.log(res.data)
                  })
                  .catch((err) => {
                    console.log(err);
                    // setLoading(false);
                })
              
       }
      //  console.log(asset)

useEffect(()=>{
  // setAsset (getAssets())
  getAssets();
},[])


  return (
    <>
     <NavBar/>
    
  <table className="table-bordered">
   <thead>
   <tr>
       <td>Full Name</td>
       <td>Model</td>
       <td>Serial</td>
         </tr>
        </thead>

             <tbody>
          {
         asset.map((item,k)=>{
              return(
                <tr key={k}>
                   <td>{item.fullName}</td>
                  <td>{item.model}</td>
                  <td>{item.serial}</td>
                </tr>
              )
            })
          }
             </tbody>
       </table>

    
    </>
  )
}

export default AssetList

import express from "express";
import mongoose, { Error } from "mongoose";
import bodyParser from "body-parser";
import cors from 'cors';
import assetrouter from "./router/assetDetail.router";

const app = express()
const port = 6001

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

var corsOptions = {
    // origin: 'http://localhost:5000',---
    optionsSuccessStatus: 200, // For legacy browser support
    methods: "GET, PUT, PATCH,  POST, DELETE"
}

app.use(cors(corsOptions));

app.listen(port, () =>{
    console.log(`example app listening on port ${port}`)
})
mongoose.connect("mongodb://127.0.0.1:27017/vaibhav")
 .then(()=>{
    console.log("Database Connected Successfuly!!!!")})
 .catch((err)=>{ 
    console.log("Error:",err)})

    app.use('/assets',assetrouter)

2

Answers


  1. try to change
    setAsset([res.data])
    to be setAsset([...res.data]) or setAsset(res.data)

    update :

    Here’s what you can do to fix the problem:

    Update the getAssets function to properly format the response data:

    const getAssets = () => {
      axios
        .get('http://localhost:6001/assets/get-assets')
        .then((res) => {
          const data = res.data; // assuming the response data is an array of objects
          setAsset(data); // set the state to the formatted data
          console.log(data);
        })
        .catch((err) => {
          console.log(err);
        });
    };
    

    In the asset.map function, you need to access the object properties by their names instead of trying to access them directly from the array:

        {
      asset.map((item, k) => {
        return (
          <tr key={k}>
            <td>{item.fullName}</td>
            <td>{item.model}</td>
            <td>{item.serial}</td>
          </tr>
        );
      });
    }
    

    Also, make sure that you have imported the required modules such as React and useState correctly.

    Login or Signup to reply.
  2. Change the line setAsset([res.data]) to setAsset(res.data). This assumes that the API response is an array of objects representing individual assets.

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