Compiled with problems:X
ERROR
src\component\Products.jsx Line 8:34: React Hook "useState" is called in function "getAllProducts" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
I'm trying to use useState, what is the best way to fetch the data from database to frontend
import React, { useState } from 'react';
import { NavLink } from 'react-router-dom';
import DATA from '../Data';
const getAllProducts = () => {
const [products, getproducts] = useState({
title : '',
price : '',
image : ''
});
const {title, price, image}= products;
let getproduct = fetch('http://localhost:6000/products/allProducts', {
method : 'GET',
headers : {
'Content-Type':'application/json'
},
body : JSON.stringify({
title, price, image
})
})
const cardItem = (item) => {
return(
<div className="card mx-3 my-5 py-3 px-2" key={item.id} style={{width: "15rem"}} id="cards">
<img src={item.image} className="card-img-top" alt={item.title} />
<div className="card-body text-center">
<h5 className="card-title fw-bolder" id="para">{item.title}</h5>
<p className="lead fw-bold" id="para">${item.price}</p>
<NavLink to={`products/${item.id}`} className="btn btn-outline-danger fw-bolder px-5 rounded-pill" id="para">Buy Now</NavLink>
</div>
</div>
);
}
return (
<div>
<div className="container py-2 mt-5 pt-5">
<div className="row">
<div className="col-12 text-center">
<h1 className="display-6 fw-bolder text-center" id="late">Latest Collections</h1>
<hr/>
</div>
</div>
</div>
<div className="container" id="products">
<div className="row justify-content-around">
{getproduct.map(cardItem)}
</div>
</div>
</div>
);
}
export default getAllProducts;
Hi
First I notify you of errors in your code and then expose you a solution:
I would advise you this one , it's near of what you have done.
We create a method to get the data, a state to store the data and we display them conditionally
In my example below I use the axios library, it is an alternative to the fetch method that you use but the principle remains the same with the fetch method (except for one line of code)
I hope it helps you