Home > Blockchain >  React JS Class Component - Set Sate
React JS Class Component - Set Sate

Time:07-04

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;

CodePudding user response:

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?

  • Related