skip to Main Content

I’m getting an error called "Uncaught TypeError: product.color?.map is not a function" i’m getting this error when i try to map the color of product is single product page

<Filter>
   <FilterTitle>Color</FilterTitle>
      {product.color?.map((c)=>(
      <FilterColor color={c} key={c} />
   ))}
</Filter>

my console log image

I fetching product data form here

const Product = () => {
    const location = useLocation();
    const id = location.pathname.split("/")[2];
    const [product, setProduct] = useState({});
  
    useEffect(() => {
      const getProduct = async () => {
        try {
          const res = await publicRequest.get("/products/find/" + id);
          setProduct(res.data.product);
        //   console.log(res);
        } catch(error) {
            console.log(error);
        }
      };
      getProduct();
    }, [id]);

This is the data i received

the data

2

Answers


  1. The effect is going to be called after the component is initially rendered, therefore in the first render, the product.color is undefined. And it seems that color is a string, not an array therefore you do not need to use map, just display the result.

    You can put a conditional to only render when you get the result from the API:

    <Filter>
       {product.color !== undefined &&
         <FilterTitle>Color</FilterTitle>
         <FilterColor color={product.color} key={product.color} />
       }
    </Filter>
    
    Login or Signup to reply.
  2. Based on the data you provided, a product.color is a single object so, you can’t use the map in a single object.

    <Filter>
       <FilterTitle>Color</FilterTitle>
       <FilterColor color={product[1].color} /> // pass the product[0].color value
    </Filter>
    

    If you want to map then you have to map the product which has multiple objects

     <Filter>
      <FilterTitle>Color</FilterTitle>
      {product.map((product, index) => (
        <React.Fragment key={index}>
          <FilterColor color={product.color} />
          <div>Price: {product.price}</div>
          <div>Size: {product.size}</div>
          {/* add more product details here as needed */}
        </React.Fragment>
      ))}
    </Filter>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search