Search code examples
reactjsoptional-chaining

Cannot read properties of null (reading 'length') in reactJs


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>
            ))}

Solution

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