I am trying to render the response from Axios in reactjs. The response is data from the MySQL database. Please see my code below and am getting the error message Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
I will appreciate any assistance. Thanks.
const Products = () => {
const fd = () => {
return Axios.get("http://localhost:5000/popular-products")
.then(response => response.data)
}
return (
<Container>
{fd().then((data) => {
data.map((item)=>(
<h1>{item.prod_name}</h1>
))
})}
</Container>
);
};
export default Products;
CodePudding user response:
Best practice to resolve promise outside the JSX. You can use bellow approach if you like.
const [items, setItems] = useState([]);
const fetch = () => {
axios
.get("http://localhost:5000/popular-products")
.then((response) => setItems(response.data));
};
// component did mount
useEffect(() => {
fetch();
}, []);
return (
<div className="App">
{items.length > 0 && items.map((item) => <p key={item.id}>{item.prod_name}</p>)}
</div>
);
In here I have used component did mount to fetch data when component mounted.