DEV Community

Cover image for Building Shopping Cart Actions and Reducers with Redux
Aneeqa Khan
Aneeqa Khan

Posted on

Building Shopping Cart Actions and Reducers with Redux

This blog is about simple actions and reducers required in shopping cart app. Here I am not going to write down all the UI used for it, its only about how you can manage your state in redux store and update it accordingly.

Here I am writing actions and reducers for these five scenarios

  1. Add to cart
  2. Remove from cart
  3. Increase quantity of product
  4. Decrease quantity of product
  5. Discard cart

First we need to create three files actionTypes.js, actions.js and reducer.js. So first thing first we'll write our actionTypes.js file and define our all action types there like this.



export const ADD_TO_CART = 'ADD_TO_CART';
export const REMOVE_FROM_CART = 'REMOVE_FROM_CART';
export const ADD_QUANTITY = 'ADD_QUANTITY';
export const SUB_QUANTITY = 'SUB_QUANTITY';
export const EMPTY_CART = 'EMPTY_CART';


Enter fullscreen mode Exit fullscreen mode

Our actions.js will look like this now



export const addToCart = id => {
  return {
    type: ADD_TO_CART,
    id
  };
};
export const removeFromCart = id => {
  return {
    type: REMOVE_FROM_CART,
    id,
  };
};
export const subtractQuantity = id => {
  return {
    type: SUB_QUANTITY,
    id,
  };
};
export const addQuantity = id => {
  return {
    type: ADD_QUANTITY,
    id,
  };
};
export const emptyCart = () => {
  return {
    type: EMPTY_CART,
  };
};


Enter fullscreen mode Exit fullscreen mode

Here you need to import ur action types from actionTypes.js file above. In actions we are only getting id of products and returning to reducer with its respective action type and id. Empty/Discard cart action doesn't need any id, it will discard the whole cart.

Before writing reducer, I want to show you the sample of my products json:



"products": [
    {
      "id": 1,
      "name": "Perfume",
      "image": "https://image.shutterstock.com/z/stock-photo-vintage-red-shoes-on-white-background-92008067.jpg",
      "price": 200,
      "quantity": 1,
      "selected": false
    }
]


Enter fullscreen mode Exit fullscreen mode

Now the real work is done in reducer.js



const initialState = {
  products: [],
};
const ShoppinReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      return {
        ...state,
        products: state.products.map(product =>
          product.id === action.id ? {...product, selected: true} : product,
        ),
      };
    case REMOVE_FROM_CART:
      return {
        ...state,
        products: state.products.map(product =>
          product.id === action.id
            ? {...product, selected: false, quantity: 1}
            : product,
        ),
      };
    case ADD_QUANTITY:
      return {
        ...state,
        products: state.products.map(product =>
          product.id === action.id
            ? {...product, quantity: product.quantity + 1}
            : product,
        ),
      };
    case SUB_QUANTITY:
      return {
        ...state,
        products: state.products.map(product =>
          product.id === action.id
            ? {
                ...product,
                quantity: product.quantity !== 1 ? product.quantity - 1 : 1,
              }
            : product,
        ),
      };
    case EMPTY_CART:
      return {
        ...state,
        products: state.products.map(product =>
          product.selected
            ? {...product, selected: false, quantity: 1}
            : product,
        ),
      };
    default:
      return state;
  }
};
export {ShoppinReducer};


Enter fullscreen mode Exit fullscreen mode

so that's it, you get a basic functionality of cart done. I hope you like it and do visit my profile for more blogs. Thanks!

Top comments (6)

Collapse
 
mrsaeeddev profile image
Saeed Ahmad

Great article!

Collapse
 
aneeqakhan profile image
Aneeqa Khan

Thanku Saeed!

Collapse
 
mrsaeeddev profile image
Saeed Ahmad • Edited

You are welcome Aneeqa!

Collapse
 
alirasapour profile image
Ali Rasapour

how to use in mapDispatchToProps ??
Please Help.

Collapse
 
monmohon profile image
Mon Mohon Singha

mapDispatchToProps is dead
use hook

Collapse
 
edizle585 profile image
Elijah Logan

Import Connect from react-redux in files that contain components you want to connect to the store
Use Connect function to connect component to redux store
Use mapStateToProps to pass down store state through props

const mapStateToProps = state => {
return {
products: state.products
}
}

export default connect( mapStateToProps )( Cart );

Here is what my store looks like that's passed the Reducer
const initialState = {
products: [],
};

I hope this helps!