Discovering an Uncaught TypeError: Unable to access the property 'length' of an undefined value

Looking to implement a function that checks the status of the cart and displays output accordingly. The logic is as follows: If the cart is empty (cart.line_items.length returns false), then the EmptyCart function should be executed. The "line_items" variable is an array retrieved from the API response. The function should iterate through each item and display them in a Material-UI grid. Below is the .jsx code snippet.

import React from 'react';
import { Container, Typography, Button, Grid } from '@material-ui/core';
import useStyles from './styles.js';

const Cart = ({ cart }) => {

    const classes = useStyles();
// Function to check if cart is empty or filled
    const isEmpty = !cart.line_items.length;

    const EmptyCart = () => (
        <Typography variant="subtitle1"> Your cart is Empty </Typography>
    );

    const filledCart = () => (
        <>
            <Grid container spacing={3}>
                {cart.line_items.map((item) => (
                    <Grid item xs={12} sm={4} key={item.id}>
                        <div>{item.name}</div>
                    </Grid>
                ))}
            </Grid>
            <div className={classes.cardDetails}>
                <Typography variant="h4">
                    Subtotal: {cart.subtotal.formatted_wih_symbol}
                </Typography>
                <div >
                    <Button className={classes.emptyButton} size="large" type="button" variant="contained" color="secondary" > Empty Cart </Button>
                    <Button className={classes.checkoutButton} size="large" type="button" variant="contained" color="primary" >Checkout</Button>
                </div>
            </div>
        </>
    );

    return (
        <Container>
            <div className={classes.toolbar} />
            <Typography className={classes.title}>Your Shopping Cart</Typography>
            {isEmpty ? <EmptyCart /> : <filledCart />}
        </Container>
    )
}

export default Cart

Answer №1

Ensure to verify whether cart.line_items is either null or undefined.

As shown here:

const checkEmpty = !cart.line_items || !cart.line_items.length;

Answer №2

To include an extra verification for undefined, you can utilize the optional chaining feature in JavaScript as shown below:

const isEmpty = !cart.line_items?.length;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

Is it possible to use the AngularJS function with the <div> HTML element?

I am facing an issue with displaying a modal when clicking on a <div> element. The function assigned to show the modal by changing the CSS property 'display' from 'none' to 'block' works fine when attached to a button, b ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

Send the checkbox value using ajax, jquery, and php

Hey everyone, I'm facing an issue and need some help. I am trying to send the value of a checkbox via AJAX to a PHP file. My question: I want to pass the checkbox value regardless of whether it is checked or not. If it is checked, then the value "tr ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

What is the best way to send the value of this variable through the parameters?

In jQuery: initializeSliders(socket, '!{requestData}'); requestData is a special object (an HTTP request object in my Express.js web application) that contains information such as my session. However, when I pass this object into the initialize ...

Ensuring Sequential AJAX Calls in jQuery for Optimal Performance

I recently transitioned some code to FastCGI for backend processing of AJAX requests from a jQuery-driven front end. While FastCGI has generally sped up the process, I've encountered a performance drawback when two jQuery AJAX requests are made in rap ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

Exploring node-validator's capabilities with asynchronous validation

Currently tackling my initial Node.js venture and facing a roadblock. Utilizing node-validator for input validation and working with Sequelize as an ORM. The Dilemma of Async Validation Striving to create custom validation to verify username availability ...

How to focus on an input element in Angular 2/4

Is there a way to focus on an input element using the (click) event? I'm attempting to achieve this with the following code, but it seems like there may be something missing. (I am new to Angular) sTbState: string = 'invisible'; private ele ...

An object will not be returned unless the opening curly bracket is positioned directly next to the return statement

compClasses: function() { /* The functionality is different depending on the placement of curly brackets */ return { major: this.valA, minor: this.valB } /* It works like this, please pay attention to ...

Unable to shrink array within an object

I'm encountering an issue while trying to reduce an array within an object. The error message I receive is: push is not a function To begin, I initialized my arrays as empty and created an add function to use as the first argument: function add(a,b ...

Issues with Material UI React Input functionality discovered following upgrade to version 4.0.0

Since updating from "@material-ui/core": "3.9.2", to "@material-ui/core": "^4.0.0-rc.0",, I have encountered some CSS problems. For instance, in the case of Input, certain CSS such as height: auto !important; appears to be missing: https://i.stack.imgur. ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

Getting the nested object property with pluck using Lodash

I have an array of objects containing character information: var characters = [ { 'name': 'barney', 'age': 36, 'salary':{'amount': 10} }, { 'name': 'fred', 'age': ...

Manipulate and transform elements within an array using both Filter and Map functionalities in React

Below is the component I am working with: function Params(props) { const { Parameters } = useFetchParams(); return ( <div className='Params'> { Parameters && Parameters.map(parameter =&g ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

What is the best option: using a Javascript template or exploring another

Just starting out in web development. I want to include the same menu on every page of my new website, but I don't want to manually update it in each file whenever there's a change. Is there an easy template engine for JavaScript or another sol ...