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
try to change
setAsset([res.data])
to be
setAsset([...res.data])
orsetAsset(res.data)
update :
Here’s what you can do to fix the problem:
Update the getAssets function to properly format the response data:
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:
Also, make sure that you have imported the required modules such as React and useState correctly.
Change the line
setAsset([res.data])
tosetAsset(res.data)
. This assumes that the API response is an array of objects representing individual assets.