score:1

Accepted answer

issue

the changeamount is changing a "global" amount value, which seems more like a total item count than anything else.

solution

the amount and total seem to be derived state, so they should just be computed when the cart is updated. i suggest you simply use the addtocart action to add a product and move the logic of determining if it's already in the cart into the reducer. create a "cartitem" object to hold the product detail and the quantity.

update the reducer function

const initialsate = {
  products: {},
  cart: [],
  total: 0,
}

export function productreducer(state = initialsate, action) {
  switch(action.type) {
    case change_products:
      return {
        ...state,
        products: action.payload,
      }
    case add_to_cart:
      const item = action.payload;
      const isincart = state.cart.some(({ id }) => id === item.id);

      let nextcart;
      if (isincart) {
        nextcart = state.cart.map(cartitem => cartitem.id === item.id ? {
          ...cartitem,
          quantity: cartitem.quantity + 1,
        } : cartitem);
      } else {
        nextcart = [...state.cart, { ...item, quantity: 1 }];
      }
      return {
        ...state,
        cart: nextcart,
        total: nextcart.reduce((total, { price, quantity }) => total + price * quantity, 0),
      }
    default:
      return state
  }
}

now you have a cart state that includes the product details and a quantity, so the amount state isn't necessary.

adjust your ui accordingly to display the item quantity when mapping the cart state in cart instead of the passed quantity prop (that is also no longer relevant).

{!!cart && cart.length > 0 && cart.map(product => 
  <section key={product._id} >
    <h3>productos en tu carrito</h3>
    <img src={product.productpictures} /> 
    <p>price={product.price * product.quantity}</p> // <-- update price computation
    <p>prodname={product.name}</p>
    <p>cantidad:{product.quantity}</p> // <-- display product quantity
  </section>
)}

Related Query

More Query from same tag