Python_Mython79
Python_Mython79

Reputation: 147

ReactJS - TypeError: Cannot read property 'name' of undefined but it is

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:

{product.map((item, idx)=>
            <div key={idx}>
                    <h3 className='productName'>{item[idx].name}</h3>
                    <div className='productImageContainer'>
                        <img src={item[idx].image}></img>
                    </div>
                    <span className='productPrice'><strong>${item[idx].Price}.00</strong></span>
                    <br></br>
                    <Button className='removeProductButton' variant='danger'><MdCancel></MdCancel> Remove</Button>

            </div>)}

And here's the piece of code where I attach the items to the array:

    const [product, getProduct]= useState([])
const getProducts=()=>
{
    let X = JSON.parse(localStorage.getItem('products'))
    getProduct([...product, X])
}

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?

Upvotes: 0

Views: 117

Answers (2)

lioncodes
lioncodes

Reputation: 11

When you are mapping through an array you are already going through each element, that is what the 'item' field in your code is. It is the each individual item from the array that you're mapping.

Now coming to why it throws up the error: When you are mapping through an array and you are inside a particular item, and you try to do item[idX].name, it is trying to find the object with the key of value idX in your case which is undefined and since it is undefined it throws up the error that it cannot read the property 'name' (which you're trying to access) of undefined.

Solution:

Hope this clears your doubt :)

Upvotes: 1

dwosk
dwosk

Reputation: 1257

You can access the name property directly on item like so:

<h3 className='productName'>{item.name}</h3>

item is the current element that is being processed in your list.

Upvotes: 1

Related Questions