-1

I have been stuck on this error for an hour now and nothing i do seems to resolve it. What am i missing? Shouldn't the optional chaining on the array maping resolve this issue?

            <h2>Cart Items</h2>
            <div>
                {cartItems?.length === 0 && <div>Cart is empty</div>}
            </div>
            {cartItems?.map((e) => (
                <div key={e.id} className="row">/*error is on this line
                    <div className='col-2'>{e.name}</div>
                    <div className='col-2'>
                        {e.qty} x {e.qty*e.price.toFixed(2)}kr
                    </div>
                </div>
            ))}
noob_coder
  • 21
  • 6
  • There's no reference to `length` in your code provided. Are you debugging in the right place? – Brian Thompson Apr 08 '22 at 17:16
  • [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) Also see [ask] and [mre]. – Ken White Apr 08 '22 at 17:24
  • I am referencing to length further up in the code. – noob_coder Apr 08 '22 at 17:26
  • 1
    If the error says reading `length`, then it has nothing to do with `map` - it has to do with `length`. The part you've included does appear to be covered with optional chaining. Does the error include a stack trace or line number? I would guess that this is either not the right place in the code, or maybe you're using a cached version of the code? – Brian Thompson Apr 08 '22 at 18:41
  • Yes you were right! The `length` was the problem, i was just confused cause the error was pointing at a different line in my code. – noob_coder Apr 09 '22 at 08:25

2 Answers2

1

The error is not thrown during mapping but while reading .length prop on cartItems array.

Cesare Polonara
  • 3,473
  • 1
  • 9
  • 19
-2

I think the optional-chaining there ensures cartItems is not null but that doesn't mean there could be null values inside the Array.

For example: [{ a: 1 }, null] is valid but reading properties during the mapping will fail.

I would make sure cartItems is clean.