I'm trying to access data from commerceJS API fetched on a different module and passed down as a prop, the code only breaks when I call a nested product object with this error Uncaught TypeError: Cannot read properties of undefined (reading 'source').
I have used the same API on the storefront and {product.media.source} works fine. I'm trying to make a preview module and when I call the nested object it breaks.
Please help.
Here's my code
const Preview = ({ products, onAddToCart }) => {
const [product, setProduct] = useState({});
const params = useParams();
const findProduct = (id) => {
return products.find((product) => {
setProduct(product);
return product.id === id;
});
};
const productId = params.id;
useEffect(() => {
findProduct(productId);
});
return (
<Card sx={{ maxWidth: 345 }} style={{ marginTop: '90px' }}>
<CardMedia image={product.media.source} title={product.name}></CardMedia>
<CardContent>
<Typography gutterBottom variant='h5' component='div'>
{product.name}
</Typography>
<Typography
variant='body2'
color='textSecondary'
dangerouslySetInnerHTML={{ __html: product.description }}
></Typography>
</CardContent>
<CardActions>
<IconButton component={Link} variant='outlined' to='/'>
Go Back
</IconButton>
<IconButton aria-label='Add to Cart' onClick={() => onAddToCart(product.id, 1)}>
<AddShoppingCart />
</IconButton>
</CardActions>
</Card>
);
Here's the product Object product obj