Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

I get undefined because item from cartitems is not undefined, how can I fix it?

1.

import React,{useState} from 'react'
import {products} from './data'

function app() {
  const [cartitems, setCartitems] = useState([])

  const onAddToCart = (product)=>{

    const exist = cartitems.find((item)=> {
        return product.id == item.id
    })

    if(exist){
      setCartitems(cartitems.map((item)=>{
        item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item
      }))
    }
    else{
      setCartitems([...cartitems, {...product, qnty: 1}])

    }
  }

  return (
    <div>
      {products.map((product)=>(
              <div key={product.id}>
      <img src={product.image} style=         {{width:"200px"}}/>
      <p>{product.name}</p>
      <button onClick={() => onAddToCart(product)}>Add To Cart</button>
    </div>
      ))}
    </div>
  )
}

export default app
export const products = [
    {
        id: '1',
        name: 'MacBook',
        price: 1400,
        image: 'https://picsum.photos/id/180/2400/1600',
      },
      {
        id: '2',
        name: 'Old Car',
        price: 2400,
        image: 'https://picsum.photos/id/111/4400/2656',
      },
      {
        id: '3',
        name: 'W Shoes',
        price: 1000,
        image: 'https://picsum.photos/id/21/3008/2008',
      },
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is: you don’t return anything here in .map. That’s why you are getting undefined.

setCartitems(cartitems.map((item)=>{
   item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item
}))

Just remove { and }:

setCartitems(cartitems.map((item)=>
   item.id == product.id ? {...exist, qnty: exist.qnty + 1}: item
))

Or add return explicitly:

cartitems.map(item => {
    if (item.id == product.id) {
      return { ...exist, qnty: exist.qnty + 1 }
    }
    
    return item
  })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading