Home > other >  how to fixed this ERROR TypeError: Cannot read properties of undefined (reading 'length')
how to fixed this ERROR TypeError: Cannot read properties of undefined (reading 'length')

Time:10-10

const Cart = ({ cartItems }) => {
  return (
    <div className="cart-items">
      <div className="cart-items-header">Cart Items</div>

      {cartItems.length === 0 && (
        <div className="cart-items-empty">No items are added.</div>
      )}
    </div>
  )
}

CodePudding user response:

It seems that cartItems its undefined. For preventing this kind of error, its better to check whether cartItems is undefined or not. So Try this :

const Cart = ({ cartItems }) => {
  return (
    <div className="cart-items">
      <div className="cart-items-header">Cart Items</div>

      {cartItems && cartItems.length === 0 && (
        <div className="cart-items-empty">No items are added.</div>
      )}
    </div>
  )
}

CodePudding user response:

Well, the error says that it's not defined, meaning , either you didn't pass it as a prop , or the value you passed is undefined(not array)

Just go to parent component, and try to debug there

CodePudding user response:

As Ploppy said in one of the comments, it simply means that cartItems is undefined. You now have 2 options

  1. Ternary operator option: In the same ternary operator you are currently using you can check if cartItems is undefined BEFORE accessing its length. Indeed it solves the problem but cannot be considered best practice.
    const Cart = ({ cartItems }) => {
      return (
        <div className="cart-items>
          <div className="cart-items-header">Cart Items</div>
          { cartItems && cartItems.length === 0 && (
             <div className="cart-items-empty">No items are added.</div>
          )}
        </div>
      )
}
  1. TypeScript option: Another option would be to convert the codebase you are currently using into a TypeScript project to handle in the most efficient way type errors you might encounter.

I've made a simple CodeSandbox to show you how Type management is handled in your case. TypeScript codesandbox

  • Related