Member-only story

Building Shopping Cart Actions and Reducers with Redux

Aneeqa Khan
2 min readApr 9, 2020

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';

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,
};
};

--

--

Aneeqa Khan
Aneeqa Khan

Written by Aneeqa Khan

I’m a frontend web and mobile developer specialized in web/mobile designs and frontend frameworks. I usually work with React, React Native, Next and TypeScript.

Responses (1)