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

Time:02-10

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 ?

CodePudding user response:

You can use optional chaining.

props?.exercices?.map(...)

CodePudding user response:

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>
  }
  • Related