0

I'm just trying to update the state of totalItems and total price. I've created the logic within the cart class component below but I'm receiving the following errors:

  1. Cart.js:24 Uncaught TypeError: Cannot read properties of undefined (reading 'length') at Cart.render (Cart.js:24:1) at finishClassComponent (react-dom.development.js:19752:1)

  2. [Violation] 'message' handler took 177ms

I am assuming I need to include setState somewhere in each statement but I'm not sure where. Can you please assist?

class Cart extends Component{
    constructor(props){
        super(props)
this.state={
    shoppingCart:[]
}

this.state = {
    totalItems: 0,
    totalPrice: 0
}
        
    }
    render(){
     
const cartItems = JSON.parse( localStorage.getItem('cart'));

const totalItems =  this.state.cartItems.length; 
const  totalPrice =  this.cartItems.map(item => item.amount).redeuce((prev, curr)=> prev + curr,0 ); 
return(<>
<div>
<h2>YOUR CART</h2>
<p># Of Items: <span>{totalItems}</span></p>
<p>Total Price: <span>{totalPrice}</span></p>
<p>Check Out</p>
</div>
      <div className="container prod-cntr">
        <div className="row prod-row">
          {cartItems?.map((element) => (
            <div className="col-lg-3 prod-col" key={element.id}>
              <div className="card card-container">
                <img
                  src={element.image}
                  alt="product img"
                  className="prod-img"
                />
                <div className="card-body">
                  <p className="card-title">{element.product}</p>
                  <p className="card-text">{element.description}</p>
                 <p className ="quantity"><span className="decrease"><i className="fa-solid fa-minus"></i></span>Quantity: <span className ="increase"><i className="fa-solid fa-plus"></i> </span></p>
                  
                </div>
              </div>
            </div>
          ))}
        </div>
        <div>
        </div>
      </div>

        </>)
    }
}

export default Cart;

1 Answer 1

1

The state doesn't have an array named cartItems. So it gives error for this.state.cartItems.length. Do you mean this.state.shoppingCart.length?

Sign up to request clarification or add additional context in comments.

1 Comment

Okay. That helps. I'm referring to the variable cartItems so I guess I need to add that to the state. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.