I’m trying to loop through an array called "experiences". When I run the code below I get this error:
TypeError: Cannot read properties of undefined (reading ‘map’)
How do I fix this?
const ProjectCard = ({ experience }) => {
return (
<div>
<div>
<h2>{experience.title}</h2>
<h3>{experience.organization}</h3>
</div>
</div>
)
}
const Projects = () => {
return (
<Layout>
<div>
{experiences.map((experience, index) => (
<ProjectCard key={index} experience={experience}/>
))}
</div>
</Layout>
)
}
I tried renaming some of the variables because I thought maybe I had accidentally overlapped some of them but that didn’t seem to work.
3
Answers
try using Array.isArray(experience) to make sure experience is array
{Array.isArray(experience) && experiences.map((experience, index) => (
))}
experiences is undefined, and hence you get
Hence you can make sure experiences is not null or undefined…
There are many ways to do it.
(experiences || []).map – or
(experiences ?? []).map
This will use empty array if experiences is undefined or null
make sure the experiences variable is an array or initialize it to an empty array initially in useState Hook
or you can use Logical &&