'Not able to display fetched data on page, React JS
I am unable to display fetched data on page. Here I am using ReactJS for frontend and NodeJS for backend. To store data I am using blockchain (hyperledger fabric)
Frontend: ReactJS,
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
const AllProduct = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
);
console.log(data.response);
setProducts(data.response);
console.log(products);
};
const display = () => {
return (products || []).map(product => (
<tr key={product.id}>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>
) );
}
useEffect(() => {
fetchProducts();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Area</th>
<th>Owner Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
{display()}
</tbody>
</table>
</div>
)
}
export default AllProduct;
I am not able to display it on page. In frontend I have used ReactJS and in backend I have used nodeJS, Hyperledger Fabric and CouchDB database
Solution 1:[1]
Following changes needed in your code
displayis function so you should call it likedisplay()place
display()inside<tbody>keyprops while usingmap()functionconst display = () => { if(products.length===0) return null; return products.map(product => ( <tr key={product.id}> <th>{product.id}</th> <th>{product.name}</th> <th>{product.area}</th> <th>{product.ownerName}</th> <th>{product.cost}</th> </tr> ) ); }-
setProducts(JSON.parse(data.response));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
