I am building a React app that is requesting data from an an Api.here i am fecting data from api and i want to display it on a table. I am using ReactJS in frontend and NodeJS in backend.
here is my code.
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
function SearchProduct() {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryProductById/1"
);
let parseData = JSON.parse(data.response)
setProducts(parseData);
};
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 SearchProduct;
i am getting uncaught error.
typeof data.response //is string
typeof products //is object
I have done almost every solution available but still can't resolve my error.
try this code:
import React, { useState, useEffect } from "react";
import "../all.css";
import Axios from "axios";
function SearchProduct() {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryProductById/1"
);
let parseData = JSON.parse(data.response);
setProducts(parseData);
};
useEffect(() => {
fetchProducts();
}, []);
//console.log(products)
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Area</th>
<th>Owner Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
{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>
))}
</tbody>
</table>
</div>
);
}
export default SearchProduct;