57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
|
|
export interface CartItem {
|
|
id: string;
|
|
productId: string;
|
|
title: string;
|
|
price: number;
|
|
quantity: number;
|
|
image?: string;
|
|
}
|
|
|
|
interface ShoppingCartState {
|
|
items: CartItem[];
|
|
}
|
|
|
|
const initialState: ShoppingCartState = {
|
|
items: typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('cart') || '[]') : [],
|
|
};
|
|
|
|
export const shoppingCartSlice = createSlice({
|
|
name: 'shoppingCart',
|
|
initialState,
|
|
reducers: {
|
|
addToCart: (state, action: PayloadAction<CartItem>) => {
|
|
const existingItem = state.items.find((item) => item.productId === action.payload.productId);
|
|
if (existingItem) {
|
|
existingItem.quantity += action.payload.quantity;
|
|
} else {
|
|
state.items.push(action.payload);
|
|
}
|
|
localStorage.setItem('cart', JSON.stringify(state.items));
|
|
},
|
|
removeFromCart: (state, action: PayloadAction<string>) => {
|
|
state.items = state.items.filter((item) => item.productId !== action.payload);
|
|
localStorage.setItem('cart', JSON.stringify(state.items));
|
|
},
|
|
updateQuantity: (state, action: PayloadAction<{ productId: string; quantity: number }>) => {
|
|
const item = state.items.find((item) => item.productId === action.payload.productId);
|
|
if (item) {
|
|
item.quantity = action.payload.quantity;
|
|
if (item.quantity <= 0) {
|
|
state.items = state.items.filter((i) => i.productId !== action.payload.productId);
|
|
}
|
|
}
|
|
localStorage.setItem('cart', JSON.stringify(state.items));
|
|
},
|
|
clearCart: (state) => {
|
|
state.items = [];
|
|
localStorage.removeItem('cart');
|
|
},
|
|
},
|
|
});
|
|
|
|
export const { addToCart, removeFromCart, updateQuantity, clearCart } = shoppingCartSlice.actions;
|
|
|
|
export default shoppingCartSlice.reducer;
|