skip to Main Content

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


  1. 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>
        );
    }
    Login or Signup to reply.
  2. 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>
      );
    }
    
    
    Login or Signup to reply.
  3. 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>
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search