Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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',
      },
]

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

this can fix your issue:

1- you didnt return anything from map

2- it's better to use function type in set state for cartitems

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(s=>[...s, {...product, qnty: 1}])

    }
  }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Problem

In your initial render, you are trying to access a property that doesn't exist. in other word, in your initial render, your products is an empty array

Solution

Use short circuting

      {products &&
            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>
            ))}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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
  })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda