42 lines
1.0 KiB
TypeScript
42 lines
1.0 KiB
TypeScript
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
|
|
|
|
export interface Product {
|
|
id: number;
|
|
title: string;
|
|
price: number;
|
|
quantity: number;
|
|
desc: string;
|
|
image: string;
|
|
}
|
|
|
|
|
|
const initialState = {
|
|
products: [],
|
|
}
|
|
|
|
export const cartSlice = createSlice({
|
|
name: "cart",
|
|
initialState,
|
|
reducers: {
|
|
addToCart: (state: any, action: PayloadAction<Product>) => {
|
|
const item = state.products.find((p:Product) => p.id === action.payload.id);
|
|
if(item) {
|
|
item.quantity += action.payload.quantity;
|
|
} else {
|
|
state.products.push(action.payload);
|
|
}
|
|
},
|
|
removeFromCart: (state, action) => {
|
|
state.products = state.products.filter((p:Product) => p.id !== action.payload);
|
|
},
|
|
resetCart: (state) => {
|
|
state.products = [];
|
|
},
|
|
},
|
|
});
|
|
|
|
export const { addToCart, removeFromCart, resetCart } = cartSlice.actions;
|
|
|
|
export default cartSlice.reducer;
|
|
|
|
export const dynamic = 'force-dynamic' |