Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error.
Here is my file structure:
- app
- components
- Product.js
- pages
- Products
- [id].js
- Products
- layout.js
- page.js
- components
[id].js
const ProductDetail = () => {
const router = useRouter();
const { id } = router.query;
const [product, setProduct] = useState(null);
useEffect(() => {
if (id) {
fetch(`https://fakestoreapi.com/products/${id}`)
.then((response) => {
if (!response.ok) {
throw new Error('Failed to fetch product');
}
return response.json();
})
.then((data) => setProduct(data))
.catch((error) => console.error(error));
}
}, [id]);
if (!product) {
return <p>Loading...</p>;
}
return (
<div>
<h1 className="text-3xl font-bold text-center my-4">{product.title}</h1>
<div className="flex justify-center">
<img
src={product.image}
alt={product.title}
className="mx-auto w-64 h-64"
/>
</div>
<p className="text-lg font-semibold mt-2 text-center">${product.price}</p>
</div>
);
};
export default ProductDetail;
Product.js
const Product = ({ product: { image, title, price, id } }) => {
return (
<div>
<Link href={`/products/${id}`}>
<div className="product-card">
<h1>Product</h1>
<img
src={image}
width={250}
height={250}
className="product-image"
/>
<p className="product-name">{title}</p>
<p className="product-price">₹{price}</p>
</div>
</Link>
</div>
)
}
page.js
"use client";
const Home = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch('https://fakestoreapi.com/products')
.then((response) => response.json())
.then((data) => setProducts(data));
}, []);
return (
<>
<div className="products-container">
{products?.map((product) => <Product key={product.id} product={product} />}
</div>
</>
);
};
export default Home;
I have attempted changing the folders for dynamic [id] and Product but without any success.