diff options
author | 2024-09-05 18:48:20 +0100 | |
---|---|---|
committer | 2024-09-05 18:48:20 +0100 | |
commit | 1ddef0eb49ebe717a638cf81a0458fa9052d8734 (patch) | |
tree | 02cae3dee2e3fb53b369c5c70ebf6210423d3413 | |
parent | Add toast container (diff) |
Add cart slice
-rw-r--r-- | thallium-frontend/src/slices/cart.ts | 46 | ||||
-rw-r--r-- | thallium-frontend/src/store.ts | 2 |
2 files changed, 48 insertions, 0 deletions
diff --git a/thallium-frontend/src/slices/cart.ts b/thallium-frontend/src/slices/cart.ts new file mode 100644 index 0000000..715fef4 --- /dev/null +++ b/thallium-frontend/src/slices/cart.ts @@ -0,0 +1,46 @@ +import { createSlice } from "@reduxjs/toolkit"; + +interface CartItem { + product_template_id: number, + quantity: number, + variant_id: number, + estPrice: string, +} + +const cartSlice = createSlice({ + name: "cart", + initialState: { + cart: [] as CartItem[], + }, + reducers: { + addCartItem(state, action: { payload: { product_template_id: number, variant_id: number, estPrice: string } }) { + const existingItem = state.cart.find((item) => item.product_template_id === action.payload.product_template_id && item.variant_id === action.payload.variant_id); + + if (existingItem) { + existingItem.quantity += 1; + return; + } + + state.cart.push({ + product_template_id: action.payload.product_template_id, + quantity: 1, + variant_id: action.payload.variant_id, + estPrice: action.payload.estPrice, + }); + }, + removeCartItem(state, action: { payload: CartItem }) { + const existingItem = state.cart.find((item) => item.product_template_id === action.payload.product_template_id && item.variant_id === action.payload.variant_id); + + if (existingItem) { + existingItem.quantity -= 1; + if (existingItem.quantity === 0) { + state.cart = state.cart.filter((item) => item.product_template_id !== action.payload.product_template_id && item.variant_id !== action.payload.variant_id); + } + } + }, + }, +}); + +export const { addCartItem, removeCartItem } = cartSlice.actions; + +export default cartSlice.reducer; diff --git a/thallium-frontend/src/store.ts b/thallium-frontend/src/store.ts index d9b4873..30766d0 100644 --- a/thallium-frontend/src/store.ts +++ b/thallium-frontend/src/store.ts @@ -1,9 +1,11 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit"; import authorizationReducer from "./slices/authorization.ts"; +import cartReducer from "./slices/cart.ts"; const rootReducer = combineReducers({ authorization: authorizationReducer, + cart: cartReducer, }); export const setupStore = (preloadedState?: Partial<RootState>) => { |