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

Unhandled Runtime Error TypeError: subSector.map is not a function

I’m unable to map through json data from a fake api. It’s working when returning more than one data but this error happens when the data is a single object.

Here is my code:

    {subSector
     ? subSector.map((sector) => (
//               ^ ~ subSector.map is not a function
         <MenuItem value={sector.id}>{sector.email}</MenuItem>
       ))
    : "nodata"}

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 :

By using map on subSector, you are assuming it is an array of items and not a single item.

You are seeing the error because subSector is not an array, and therefore does not have the map function available.

Instead, either access the subSector properties directly (assuming subSector is a single item):

    {subSector ? (
         <MenuItem value={subSector.id}>{subSector.email}</MenuItem>
       )
    : "nodata"}

or handle both cases where it could be an array or single item:

    {Array.isArray(subSector)
     ? subSector.map((sector) => (
         <MenuItem value={sector.id}>{sector.email}</MenuItem>
       ))
    : subSector ? (
         <MenuItem value={subSector.id}>{subSector.email}</MenuItem>
       ) 
    : "nodata"}

or, as catgirlkelly says, ensure your fake data always returns an array, even for a single item.

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