Redux slice managing cart state: addToCart, removeFromCart, clearCart, totals calculation, qty increment/decrement.
import { createSlice } from "@reduxjs/toolkit"
import { addLocalStorageCart, getLocalStorageCart } from '../../utils/localStorage'
const cartItems = getLocalStorageCart()
const initialState = {
cartItems: cartItems ? cartItems : [],
totalCount: 0,
totalAmount: 0,
subTotal: 0,
tax: 0
}
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
clearCart: (state) => {
state.cartItems = []
},
addToCart: (state, action) => {
let cartIndex = state.cartItems.findIndex((item) => item.id === action.payload.id)
// Increasing the quantity of the product
if (cartIndex >= 0) {
if (state.cartItems[cartIndex].quantity < state.cartItems[cartIndex].stock) {
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key