TypeError: Cannot read property 'map' of undefined, Is passing an array as a prop to a functional component not possible?

I am following a MERN stack tutorial in which a parent component Dashboard passes an array of objects from its own props (after mapStateToProps) to another component Education. Trying to iterate through this array in Education component gives me the above mentioned error. Please help, the tutorial seemed to have no errors and I have followed it perfectly so why the issue?

<Education education={profile.education}/>

(passing the prop in Dashboard.js) education is an array of objects inside an object profile which is a prop mapped from the state. The profile prop is used in other lines in the same component and does not give any other errors.

const Education = ({education}) => {
    const educations = education.map(edu => (
    <tr key={edu._id}>
        <td>{edu.institute}</td>
        <td>{edu.course}</td>
        <td>
        <Moment format='YYYY/MM/DD'>{edu.from}</Moment - <Moment 
         format='YYYY/MM/DD'>{edu.to}</Moment>
        </td>
        <td className="btn brick">
            Delete
        </td>
    </tr>
    ));

     ...return block with JSX that renders when {educations} is omitted
}

(trying to iterate in Education.js)

EDIT: Full Dashboard.js code

import React ,{Fragment,useEffect} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import {getCurrentProfile} from '../../actions/profile';
import Spinner from '../layouts/Spinner';
import DashboardActions from './DashboardActions';
import Education from './Education';

const Dashboard = ({getCurrentProfile, auth, profile}) => {

useEffect(() => {
    getCurrentProfile();
}, []);


return (
    profile.loading && profile.profile === null ? <Spinner /> : <Fragment>
        <h1 className="large text-primary">Dashboard</h1>
        <p className="lead">Welcome {auth.user && auth.user.name }</p>
        {profile.profile !== null
        ?
        <Fragment>
            <DashboardActions/>
            <Education education={profile.education}/>
        </Fragment>
        : 
        <Fragment>
            <p>You have not yet set up a profile, please add some 
information about yourself</p>
            <Link to="/create_profile" className="btn btn-primary">Create 
Profile</Link>
        </Fragment>}
    </Fragment>
    );
}

Dashboard.propTypes = {
getCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
profile: PropTypes.object.isRequired,
}

const mapStateToProps = state => ({
auth: state.auth,
profile: state.profile
});

export default connect(mapStateToProps, {getCurrentProfile})(Dashboard);

1 answer

  • answered 2019-09-10 14:28 Jonathan Irwin

    Have you tried console.log(education) to see the value of education?

    I think it is undefined while the profile is loading.

    you could try const educations = education && education.map(edu => (