score:0

if you are using sanity in your project follow the code below, it will update your quantity instead of adding the same product again in the cart, if you are not using sanity have a look at the code below i am sure it will give you some ideas to solve your problem.

update your cartslice with the code below :

const initialstate = {
  product: [],
};

export const cartslice = createslice({
  name: 'cart',
  initialstate,
  reducers: {
    addproduct: (state, { payload }) => {
      let newitem = payload;
      const existitem = state.products.find((item) => item._id === payload._id);

      state.products = existitem ? state.products.map((item) => item._id === existitem._id ? newitem : item) : [...state.products, newitem]
    }
  },
})

in the the page you want to use the reducer in add this:

const { products } = useselector(store => store.cart)

const addtocart = () => {
    let cartitem = products.find(item => item._id === product._id)
    let quantity = cartitem ? cartitem.quantity + 1 : 1;
    dispatch(() => addproduct({
        _id: product._id,
        name: product.name,
        size: product.size,
        category: product.slug.current,
        price: product.price,
        image: urlfor(product.image),
        quantity
      }))
  }

addtocart is an onclick function, you do not need to add quantity property to your json file or the api it will be added when the product is selected to be in cart. the quantity above it will check if the item does not exist in the cart the quantity will be 1 and it will be added to the object of the product item, if the item does exist in the cart it will update the quantity by one.

now everything should work just fine. if you had an error please feel free to message me, i would be more than happy to help you

score:1

assuming that there is a quantity property on your product:

    addproduct: (state, action) => {
      const item = state.product.find((pro) => pro._id === action.payload._id)
      if (item) {
        item.quantity++
      } else {
        state.product.push(action.payload)
      }
    },

Related Query

More Query from same tag