score:2

Accepted answer

includes will not work with objects. try find or findIndex instead. Also I think your check is wrong. You need to check if items has the selected productId and if yes, then update its count.

 const addCart = (productsId) => {
      setCount(count + 1)
      data.forEach((product) => {
       let index = items.findIndex(itm => itm.id === product.id && productId === product.id)
       
       if (index >= 0) {
         let newProduct = { ...items[index] }
         newProduct.count += 1
         setItem( [...item, [index]: newProduct ])
       } else {
          setItem(item.concat(product))
        }
      })
  }

score:0

Since product is an object, includes will not work as it only do "shallow" comparison like if you have a simple array (i.e ['a', 'b', 'c'].includes('c');

In your case you need to "find" the product by id to know if it exist.

 const addCart = (productsId) => {
      setCount(count + 1)
      data.forEach((product) => {

       const exist = item.find(i => i.id === product.id); // add this one

       if (exist) {
         product.count += 1
       }  else if (product.id === productsId) {
          setItem(item.concat(product))
        }
      })
  }

You can learn more about array.find here.


Related Query

More Query from same tag