Advertisements
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"}
>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.