Quiero obtener datos de una API y quiero mostrarlos en la página.
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;Recibo TypeError: products.map no es una función. Hice casi todas las soluciones que ya están presentes en stackoverflow pero no pude resolver mi error. En el frontend he usado ReactJS y en el backend he usado NodeJS
probar:
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() }, []);o prueba la solución 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(); }, []);