Search code examples
reactjsreact-nativereduxreact-reduxredux-toolkit

Update cart items quantity and price with @reduxjs/toolkit in react native


I have a cart state that holding array something like this:

 [[{"Id": 123, "duration": 10, "name": "Burger", "price": 10, "qty": 1, "total": "10.00"}]]

and this is the reducers as showing I have added to more for increase and decrease the quantity:

const cartSlice = createSlice({
    name: "cart",
    initialState: [],
    reducers: {
        addItemToCart: (state, action) => {
            state.push(action.payload); 
        },
        removeItemFromCart: (state, action) => {
            return state.filter(i => i[0].Id !== action.payload);
        },
        ADD_QUANTITY: (state, action) => {

           // notsure how to handle here 

        },
        SUB_QUANTITY: (state, action) => {
         // notsure how to handle here 
        }
    }
})

and in cart screen I am doing something like this:

  <TouchableOpacity onPress={() => dispatch(ADD_QUANTITY(item[0].Id))} >
      <Ionicons name="add-circle-outline" size={22} color="#cccccc" />
   </TouchableOpacity>

so, once the button for add quantity pressed I want to update the cart state with new qty and new total price and same when decrease quantity, it may sound a very easy question but I am a beginner and i cant figure it out.


Solution

  • Based on the input array you gave you can implement the adding and subtracting of a quantity in the array like so. You would have to loop over the state using forEach and then check if the Id matches the Id you pass in the action payload, if it is then either increment or decrement the value.

    Edit:

    Looking back I realized this was wrong and also would not work on actual data. I recommend to flatten the nested array before looping over it.

    const cartSlice = createSlice({
      name: "cart",
      initialState: [],
      reducers: {
        addItemToCart: (state, action) => {
          state.push(action.payload);
        },
        removeItemFromCart: (state, action) => {
          state.flat().filter((i) => i.Id !== action.payload);
        },
        addQuantityToItem: (state, action) => {
          state.flat().forEach((item) => {
            if (item.Id === action.payload) {
              item.qty += 1;
            }
          });
        },
        subtractQuantityFromItem: (state, action) => {
          state.flat().forEach((item) => {
            if (item.Id === action.payload) {
              item.qty -= 1;
            }
          });
        },
      },
    });
    

    Sample use case where you have to pass in the value of the id:

    <TouchableOpacity onPress={() => dispatch(addQuantityToItem(id))} >
        <Ionicons name="add-circle-outline" size={22} color="#cccccc" />
    </TouchableOpacity>