Why the product name cannot be deleted

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>
    )
}

New contributor

조민성 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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.

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);

    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>
            {product ? (
                <div className='totalpay' key={product.id}>
                    <p className='price-title'>상품가격</p>
                    <p className="product-price">{product.price}</p>
                </div>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
}

You are getting this error (The error Cannot read properties of null (reading 'price')) because product state is set to null initially

To resolve it, you can use conditional rendering to ensure that you only access product.price when product is set correctly.

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();

  useEffect(() => {
    const totalpay = total.order.products.find((product) => product.id == userid);
    setProduct(totalpay);
  }, [userid]);

  if (!product) {
//NOTE You can return  fallback UI here maybe a loading compenent
    return <div>Loading...</div>; 
  }

  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>
  );
}

The Error can also be handled as below:

  • With Optional Chaining:

    <p className="product-price">{product?.price}</p>
    
  • With Conditional Rendering:

    <p className="product-price">{product && product.price}</p>
    

I implemented it using conditional rendering and it was implemented well on the screen.

import React, { useEffect ,useState} from 'react';
import "../TotalPayMent/TotalPayMent.css"
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 className='total-title'>최종 결제금액</p>
        {product && ( 
          <div className='totalpay' key={product.id}>
            <p className='price-title'>상품가격</p>
            <p className="product-price">{product.price}원</p>
            <p className='product-coupone'>쿠폰할인</p>
            <p className='product-coupone'>{total.order.cupon}원</p>
            <p className=' product-point'>포인트 할인</p>
            <p className='product-point'>{total.order.point}원</p>
            <p className='delivery-peice'>배송비</p>
            <p className='delivery-peice'>{product.delivery}원</p>
            <div className='total'>
            <p className='total-payment'>총 결제금액</p>
            <p className='total-payment'>{product.totalprice}원</p>
        </div>
          </div>
        )}
      </div>
    )
}

New contributor

조민성 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật