skip to Main Content

Name,distribution and price are all fine only when I give category I get this error. I am giving it the way it is structured in the database and still getting the error. Problem with words? Someone will point out a little mistake kindly.

import React, { useEffect, useState } from "react";
import Layout from "../Components/Layout/Layout";
import axios from "axios";
import { useParams } from "react-router-dom";

const ProductDetails = () => {
  const params = useParams()
  const [product, setProduct] = useState({});

  // initall details
  useEffect(() => {
    if (params?.slug) getProduct();
  }, [params?.slug]);
  // getProduct
  const getProduct = async () => {
    try {
      const { data } = await axios.get(
        `/api/v1/product/get-product/${params.slug}`
      );
      setProduct(data?.product);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <Layout>
      <div className="row grid lg:grid-cols-3 m-4">
        <div className="col-1   ">
          <img
            className="w-96 h-96"
            src={`/api/v1/product/product-photo/${product._id}`}
            alt={product.name}
          />
        </div>
        <div className="col-2">
          <h1 className="text-center">Products Details</h1>
          <h4>Name: {product.name} </h4>
          <h4>Description: {product.description} </h4>
          <h4>Price: {product.price}</h4>
          <h4>Cetegory: {product.category.name}</h4>
        </div>

        <div className="col-3">
          <p>Similar Products</p>
        </div>
      </div>
    </Layout>
  );
};

export default ProductDetails;

enter image description here

2

Answers


  1. I recommend you to use product? all of the code. Also, You need to check exception on product.category.name

    Login or Signup to reply.
  2. <h4>Category: {product.category && product.category.name}</h4>
    

    This will check if product.category exists before trying to access its name property.

    Make sure to verify the structure of the API response and ensure that the category property is properly populated with the necessary data also with name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search