javascriptreact-domarray.prototype.mapreact-devtools

TypeError: Cannot read properties of undefined (reading 'length')


Working my way through my first fullstack MERN app that allows a user to add multiple places to an array. Trying to map over the array to display the number of places for the user. Code works fine until I use .length, then it crashes.

import React from 'react';

import UserItem from './UserItem';
import Card from '../../shared/components/UIElements/Card/Card';
import './UsersList.css';


const UsersList = props => {
    if (props.items.length === 0) {
        return (
            <div className="center">
                <Card>
                    <h2>No users found.</h2>
                </Card>
            </div>
        );
    }


    return (
        <ul className="users-list">
            {props.items.map(user => (
                <UserItem
                    key={user.id}
                    id={user.id}
                    image={user.image}
                    name={user.name}
                    // placeCount={user.places.length}
                    placeCount={user.places}
                />
            ))}
        </ul>
    );


};

export default UsersList;

The full error stack:

Uncaught TypeError: Cannot read properties of undefined (reading 'length')
The above error occurred in the <UsersList> component:

  
Consider adding an error boundary to your tree to customize error handling behavior.

Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
  

I did a keyword search of .length throughout the backend and frontend files to double check the code and make sure I didn't have any typos anywhere--but for the life of me I can't figure out why adding .length isn't working.

I've gone through a few different posts on here but cannot find a working solution.

Any insight would be greatly appreciated. For now I just commented out .length so I can keep working. Thank you!


Solution

  • The other answers are focusing on prop.items list but in your question you mention that you get the exception when trying to access the length of the places inside users.

    You are getting the error message because some users may not have any places listed inside them, hence, no places list -> no length property.

    To fix this, you need to check if the places list exists and then access its length:

    placeCount={ user.places ? user.places.length : 0 }
    

    Here, we use a ternary operator to check if user.places exists, then we use the length, else use zero.

    Edit: As pointed out by Phil in the comments below, you can also use coalescing operator, which is much cleaner, like this:

    placeCount={ user.places?.length ?? 0 }
    

    The syntax simply translates as if user.places has a value for length, then use that value, else use zero as a default value.