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

Cannot get the first element of array whereas map() works as a charm

In a React component want to print out the a value of an object ("name") which is the first element in the array:

"production_countries": [
  {
    "iso_3166_1": "US",
    "name": "United States of America"
  }
]

This code collapses the app with error TypeError: Cannot read properties of undefined (reading 'name'):

<p>
  {
    movie.production_countries &&
    movie.production_countries[0].name
  }
</p>

However, if I replace the code above with a .map() everything works as a charm.

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

<p>
  {movie.production_countries &&
    movie.production_countries?.map((country, i) => (
      <span key={i}>
        {country.name}
      </span>
    ))}
</p>

How can I get the first element of array? Thanks

>Solution :

production_countries could be an empty array, in which case [0] will return undefined, using ? for early return should work:

{
  movie.production_countries &&
  movie.production_countries[0]?.name
}
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