Issue
I am trying to map a array of object inside another object in react. But there is an error Type Error: Cannot read properties of undefined (reading 'map')
.
const data={
comments: [{…}],
desc: "batman"
likes: ['001']
userid: "001"
username: "name"
}
"This is what i have tried"
{data?.comments.map((val, id) => {
return (
<div className='comment-section' key={id}>
<span style={{ color: 'gray' }}><b>{val.username}</b></span>
<span> {val.comment}</span>
</div>
)
})}
Comments is an array of objects containing username, comment fields in each object.
Solution
Not totally sure, but in my case I put this
data?.comments && data?.comments?.map((val, id) => {
....
....
}
This will render the map if data.comments
is truthy
Answered By - Dave Spencer Bacay
Answer Checked By - - Mary Flores (ReactFix Volunteer)