0

I make an ecommerce site I have a page that displays all the products and on each product I put a link tag that refers to my page where I will put the product details with its id like this :

             <div className="flex -mx-5 overflow-x-scroll snap-x scrollbar-hide">
              {products.filter(p => p.category === categoryName).map(productInfo => (
                <Link href={`/product?id=${productInfo._id}`} key={productInfo._id} className="px-5 snap-start border rounded-xl shadow-md m-2 p-3 bg-white">
                 <Product {...productInfo}/>
                </Link>
              ))}
            </div>

and my page with product details where I get the id from the url :

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import axios from "axios";

import Layout from "../components/Layout";

const ProductPage = () => {
  const router = useRouter();
  const [product, setProduct] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchProduct = async () => {
      try {
        const response = await axios.get(`/api/products?id=${router.query.id}`);
        setLoading(false);
        setProduct(response.data);
        console.log(product)
      } catch (error) {
        console.error(error);
      }
    };
    
    fetchProduct();
  }, [router.query.id]);
 console.log(product)
  return (
    <Layout title={product.name}>
      {loading ? (
        <div className="text-center">Loading...</div>
      ) : (
        <div className="max-w-lg mx-auto p-5">
          <h1 className="text-2xl font-bold mb-5">{product.name}</h1>
          <img
            src={product.imageUrl}
            alt={product.name}
            className="w-full mb-5"
          />
          <p className="mb-5">{product.description}</p>
          <p className="text-xl font-bold mb-5">
            Price: {product.price} {product.currency}
          </p>
          <Link href="/" legacyBehavior>
            <a className="btn btn-primary">Go back to the products list</a>
          </Link>
        </div>
      )}
    </Layout>
  );
};

export default ProductPage;

The values ​​are not displayed so I put some console.log When I put a console.log in the "try" product returns an empty object, and when I put the console.log after the useffect the product returns an object with my values

Rip Rip
  • 31
  • 5

0 Answers0