hey guys i just wanna know, why this is happen. when i try to console.log(product.color) they show the result array of color, when i try to map the array, they show error that product is undefined. here's the code
const Product = ({ item }) => {
const params = useParams();
const id = params.id;
const [product, setProduct] = useState({});
const [quantity, setQuantity] = useState(1);
useEffect(() => {
window.scrollTo(0, 0);
}, []);
useEffect(() => {
const getProduct = async () => {
try {
const response = await axios.get(
`http://localhost:8000/api/products/find/${id}`
);
const data = await response.data.product;
setProduct(data);
} catch (error) {
console.log(error.response);
}
};
(async () => await getProduct())();
}, []);
const handleQuantity = (type) => {
if (type === 'dec') {
setQuantity(quantity > 1 ? quantity - 1 : 1);
} else {
setQuantity(quantity 1);
}
};
return (
<Container>
<Navbar />
<Announcements />
<Wrapper>
<ImageContainer>
<Image src={`${product.img}`} />
</ImageContainer>
<InfoContainer>
<Title>{product.title}</Title>
<Desc>{product.desc}</Desc>
<Price>{product.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>color</FilterTitle>
{console.log(product.color.length)}
{<FilterColor color={product.color} />}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize>
{/* {product.size.map((elem) => (
<FilterSizeOption key={elem}>{elem}</FilterSizeOption>
))} */}
<FilterSizeOption>{product.size}</FilterSizeOption>
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove onClick={(e) => handleQuantity('dec')} />
<Amount>{quantity}</Amount>
<Add onClick={(e) => handleQuantity('inc')} />
</AmountContainer>
<Button>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<NewsLetter />
<Footer />
</Container>
);
};
this part give me error
<Filter>
<FilterTitle>color</FilterTitle>
{console.log(product.color.length)}
{<FilterColor color={product.color} />}
</Filter>
the result from console.log(product.color)
Array [ "red" ]
but when i try to map product.color
Uncaught TypeError: product.color is undefined
CodePudding user response:
Rendering time Issue. On First Render product is blank, and you getting error.
Try 1
const [product, setProduct] = useState(null);
//...........
//...............
return(
<>
{product && <Container> .......... </Container>}
</>
)
Try 2
product?.color /// if color not exists it not throw error