Home > Software engineering >  Uncaught TypeError: Cannot read properties of undefined (reading 'id')
Uncaught TypeError: Cannot read properties of undefined (reading 'id')

Time:05-11

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

CodePudding user response:

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}])

    }
  }

CodePudding user response:

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

CodePudding user response:

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
  })
  • Related