0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I've tried doing that, but whenever I do it it doesn't really show anyhing unless I index it
The answer is correct though. Check your products
Most likely your products list isn't what you think it is. Doing item[idx].name isn't going to work.
I'll look into it
Hmm, yeah, apparently the product list is, for some obscure to me at least, reason empty even after I append those value to it, hmm. Thank you for the cooperation though
|
1

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.