I have a map function that is supposed to take the data from an list I’ve created and show it to the user but it give me a typerror whenever I try to do that, here’s my map function:
JavaScript
x
12
12
1
{product.map((item, idx)=>
2
<div key={idx}>
3
<h3 className='productName'>{item[idx].name}</h3>
4
<div className='productImageContainer'>
5
<img src={item[idx].image}></img>
6
</div>
7
<span className='productPrice'><strong>${item[idx].Price}.00</strong></span>
8
<br></br>
9
<Button className='removeProductButton' variant='danger'><MdCancel></MdCancel> Remove</Button>
10
11
</div>)}
12
And here’s the piece of code where I attach the items to the array:
JavaScript
1
7
1
const [product, getProduct]= useState([])
2
const getProducts=()=>
3
{
4
let X = JSON.parse(localStorage.getItem('products'))
5
getProduct([product, X])
6
}
7
I get the following error: “TypeError: Cannot read property ‘name’ of undefined”, I’ve tried manually console logging each element of the list and it is definitely not undefined, why is that happening and how can I fix it?
Advertisement
Answer
You can access the name
property directly on item
like so:
JavaScript
1
2
1
<h3 className='productName'>{item.name}</h3>
2
item
is the current element that is being processed in your list.