I'm getting the following error -
ProductDetail.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'name')
import React from 'react';
import {useParams } from 'react-router-dom';
import products from '../products';
const ProductDetail = () => {
const { id } = useParams();
const product = products.find((p) => p._id === Number(id));
return (
<div>
{product.name}
</div>
);
}
export default ProductDetail;
products.js
const products = [
{
'_id': '1',
'name': 'Samsubg A001',
'description':
'testinggggg',
'brand': 'Samsung',
'category': 'Mobile',
'price': 10,
'Stock': 20,
'rating': 4.5,
'Reviews': 12,
},
CodePudding user response:
Are you sure that product
variable is not undefined? Seems like you are trying to access to name
property inside a undefined variable.
CodePudding user response:
You can short-circuit by checking if the product is undefined or you can use optional chaining like this product?.name