Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map in map : TypeError: Cannot read properties of undefined (reading 'map')

I have these datas :

[
    {
        "id": "1",
        "name": "test1",
        "secondary": [
            "testS1", "testS2"
        ]
    },
    {
        "id": "2",
        "name": "test2",
        "secondary": [
            "testS3", "testS4"
        ]
    }
]

I map all exercices from a json file, and now I wish to loop props.exercices.secondary of each object.
Here is my try :

export default function AllExos(props) {
    return <div>
        {props.exercices.map(exo => {
            return <div key={exo.name}>
                <div>
                     <h2>{exo.id}</h2>
                     <p>Display secondary :
                            {exo.secondary.map(k => {
                                return <span key={k}>{k}</span>
                            })}
                     </p>
                 </div>
             </div>
        })}
    </div>
}

I don’t understand why I get the error TypeError: Cannot read properties of undefined (reading 'map'). I am looping in the ‘props.exercices’, right ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this condition props.exercices && props.exercices.length > 0 &&

 export default function AllExos(props) {
    return <div>
        {props.exercices && props.exercices.length > 0 && 
          props.exercices.map(exo => {
            return <div key={exo.name}>
             <div>
                 <h2>{exo.id}</h2>
                 <p>Display secondary :
                        {exo.secondary.map(k => {
                            return <span key={k}>{k}</span>
                        })}
                 </p>
              </div>
          </div>
       })}
    </div>
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading