You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.2 KiB
45 lines
1.2 KiB
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
import { calcTotalPrice } from '../../utils/calcTotalPrice';
|
|
import { getCartFromLS } from '../../utils/getCartFromLS';
|
|
import { CartItem, CartSliceState } from './types';
|
|
|
|
const initialState: CartSliceState = getCartFromLS();
|
|
|
|
const cartSlice = createSlice({
|
|
name: 'cart',
|
|
initialState,
|
|
reducers: {
|
|
addItem(state, action: PayloadAction<CartItem>) {
|
|
const findItem = state.items.find((obj) => obj.id === action.payload.id);
|
|
|
|
if (findItem) {
|
|
findItem.count++;
|
|
} else {
|
|
state.items.push({
|
|
...action.payload,
|
|
count: 1,
|
|
});
|
|
}
|
|
|
|
state.totalPrice = calcTotalPrice(state.items);
|
|
},
|
|
minusItem(state, action: PayloadAction<string>) {
|
|
const findItem = state.items.find((obj) => obj.id === action.payload);
|
|
|
|
if (findItem) {
|
|
findItem.count--;
|
|
}
|
|
},
|
|
removeItem(state, action: PayloadAction<string>) {
|
|
state.items = state.items.filter((obj) => obj.id !== action.payload);
|
|
},
|
|
clearItems(state) {
|
|
state.items = [];
|
|
state.totalPrice = 0;
|
|
},
|
|
},
|
|
});
|
|
|
|
export const { addItem, removeItem, minusItem, clearItems } = cartSlice.actions;
|
|
|
|
export default cartSlice.reducer;
|
|
|