React Redux update item quantity (more than just one increment)

I have a site where the user can increase the quantity on the product before adding it to cart. Now if the user decided to go back to the product and add 3 more by increasing the quantity on the product, then adding to cart – how do I update the quantity of the existing product in basket?

At the moment I get duplicates of the product with different quantities depending on what is selected.

Here is the code I have for my reducer:

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  items: [],
};

const basket = createSlice({
  name: "basket",
  initialState,
  reducers: {
    addToBasket: (state, { payload }) => {
        // No idea what to do with this..
      state.items.filter((pizza) => pizza.name === payload.name);

      // This pushes the item fine, but I get multiple of the same item in the cart instead of just updating its quantity
      state.items.push(payload);



      //   state.items.map((pizza) =>
      //     pizza.name === payload.name
      //       ? {
      //           ...pizza,
      //           quantity: pizza.quantity + payload.quantity,
      //         }
      //       : pizza
      //   );


    },
  },
});

export const { addToBasket } = basket.actions;
export const basketItems = (state) => state.basket.items;

export default basket.reducer;

The payload is the specific product, it will be an object:

{
 name: "product name",
 image: "url.jpeg",
 price: "14.99"
}

I can not for the life of me figure out what to do here in order not to mutate the state. Nothing works, I feel like I have tried every possible way but clearly I am missing something.

Any help much appreciated!!!

Thanks

93 thoughts on “React Redux update item quantity (more than just one increment)”

  1. Hi there, I discovered your blog by means of Google at the same time as searching for a similar topic,
    your website came up, it appears to be like good. I have bookmarked it in my google bookmarks.

    Hi there, simply become aware of your weblog through Google, and located that it’s really informative.
    I am gonna watch out for brussels. I’ll appreciate for those who proceed this
    in future. Numerous people might be benefited out of your writing.
    Cheers! http://droga5.net/

    Reply

Leave a Comment