Blog>
Snippets

Creating a Reducer for an E-commerce Cart

Showcase the use of `createReducer` in dynamically adding, updating, or removing items from a shopping cart.
import { createReducer } from '@reduxjs/toolkit';

// Action types
const ADD_ITEM = 'ADD_ITEM';
const REMOVE_ITEM = 'REMOVE_ITEM';
const UPDATE_QUANTITY = 'UPDATE_QUANTITY';

// Initial state of the cart
const initialState = {
    items: {}
};

// Reducer
const cartReducer = createReducer(initialState, {
    [ADD_ITEM]: (state, action) => {
        const { id, product } = action.payload;
        if (!state.items[id]) {
            state.items[id] = { ...product, quantity: 1 };
        } else {
            state.items[id].quantity += 1;
        }
    },
    [REMOVE_ITEM]: (state, action) => {
        delete state.items[action.payload.id];
    },
    [UPDATE_QUANTITY]: (state, action) => {
        const { id, quantity } = action.payload;
        if (state.items[id]) {
            state.items[id].quantity = quantity;
        }
    }
});
This code snippet creates a shopping cart reducer with Redux Toolkit. It defines action types for adding, removing, and updating item quantities in the cart and provides an initial empty cart state. The reducer uses createReducer to handle the state updates in an immutable way. When an item is added, it increments the quantity if the item already exists, or sets it to one. Items can be removed by deleting them from the state, and their quantities can be updated directly.