here my code i am fecthing data from api and want to display it on the page
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"
);
const products = JSON.parse(JSON.stringify(data));
setProducts(products);
console.log(products);
};
const display = () => {
return products.map(product => (
<tr>
<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>
{display}
</table>
</div>
)
}
export default AllProduct;
**But i am not able to display it on page. In frontend i have used ReactJS and in backend i hvae used nodeJS, Hyperledger Fabric and CouchDB database **
CodePudding user response:
looks like the response is in json string, either fix the backend to return an actual array/object to your liking or just parse the output like:
const products = JSON.parse(data);
And ofcourse since its an array you can't just display it like that, wrap it in a loop:
const display = () => {
return products.map(product => (
<tr>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>
);
}
then call display
inside the element
CodePudding user response:
As I can see from the screenshot at line 92 you are printing the products. So, see it is a JSON string, not the object. For that, you will need to parse this JSON and then set it in your state.
do something like this.
setProducts(JSON.parse(data));