Cannot read properties of null (reading ‘price’)
TypeError: Cannot read properties of null (reading ‘price’)
A Type Error appears on the screen.
import React, { useEffect ,useState} from 'react';
import PayMockup from '../PayMockup';
import { useParams } from 'react-router-dom';
export default function TotalPayMent(){
const total=PayMockup;
const [product, setProduct] = useState(null);
const {userid} =useParams()
console.log("userid", userid);
console.log("totalpay", total.order.products[0].price);
useEffect(()=>{
const totalpay = total.order.products.find((product) =>product.id == userid);
console.log("totalpay", totalpay);
setProduct(totalpay)
},[userid])
return(
<div className='total-payment'>
<p>최종 결제금액</p>
<div className='totalpay' key={product.id}>
<p className='price-title'>상품가격</p>
<p className="product-price">{product.price}</p>
</div>
</div>
)
}
3
Answers
The error occurs because the initial state of product is null, and you’re attempting to read the price property of null before the useEffect hook has a chance to update it.In this updated code, the component conditionally renders the price information only if product is not null. If product is null, it will render a "Loading…" message.
You are getting this error
(The error Cannot read properties of null (reading 'price'))
because product state is set to null initiallyTo resolve it, you can use conditional rendering to ensure that you only access product.price when product is set correctly.
The Error can also be handled as below:
With Optional Chaining:
With Conditional Rendering: