-
Notifications
You must be signed in to change notification settings - Fork 0
/
cartSlice.ts
57 lines (46 loc) · 1.37 KB
/
cartSlice.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
export type CartState = Record<string, number>;
const initialState: CartState = {
"2aT976Fs_Bek0e2ZR_05V": 10,
"9t2dPgRBgWpmOXRXK5l4Q": 14,
};
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
increment: (
state: CartState,
action: PayloadAction<string>
) => {
const id = action.payload;
if (id in state) {
const quantity = state[id];
state[id] = quantity + 1;
} else {
state[id] = 1;
}
},
decrement: (state: CartState, action: PayloadAction<string>) => {
const id = action.payload;
if (!(id in state)) {
return;
}
if (state[id] === 1) {
delete state[id];
return;
}
const quantity = state[id];
state[id] = quantity - 1;
},
reset: (state: CartState, action: PayloadAction<string>) => {
const id = action.payload;
if (!(id in state)) {
return;
}
delete state[id];
}
}
});
export const { increment, decrement, reset } = cartSlice.actions;
export default cartSlice.reducer;