i want to fetch data from an api and want to display it on page.
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
const AllProduct = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
return await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
).then(res=>{
setProducts(res.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 getting TypeError: products.map is not a function. i did almost every solution which is already present on stackoverflow but i didn't able to resolve my error.In frontend i have used ReactJS and in backend i have used NodeJS
try:
import React, { useState, useEffect } from 'react';
const fetchProducts = async () => {
return await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
).then(res=>{
setProducts(res.response)
})
console.log(products);
}
useEffect(() => {
fetchProducts()
}, []);
or try solution 2:
const [products, setProducts] = React.useState([]);
React.useEffect(function effectFunction() {
async function fetchProducts() {
const response = await Axios.get( "http://localhost:8080/api/QueryAllProducts");
const data= await response.data;
setProducts(data);
}
fetchProducts();
}, []);