score:0

I think filter is not the correct function to use. Filter needs to filter object. You are trying to mutate them as well inside. The filter function is immutable which means that it generates a new array instead of an old one.

     addToCarrito.filter((elemento, pos) => {
        if (elemento.item.id === item.id) {
          addToCarrito[pos].quantity += quantity; // <- mutating prev value(bad)
          return false;
        }
        return true;
      })

For this task is better to use an object, rather than an array. That will simplify a lot your code.

      const [products, setProducts] = useState({})
    
      const addProduct = (item, quantity) => {
        // if product already in the object - take it, otherwise add new with 0 quatity
        const newProduct = { ...(product[item.id] ?? {...item, quantity: 0}) }
        newProduct.quantity += 1
        setProducts(products => ({
          …products,
          [item.id]: newProduct
         }) 
        })
      }
    
      // here the array of your products, f.e. for iteration
      const productList = React.useMemo(() => Object.values(products), [products])


Related Query

More Query from same tag