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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
export interface VoteSliceState {
votes: Record<string, Record<string, number | null>>;
}
interface VoteChange {
questionId: string;
optionId: string;
change: 1 | -1;
}
interface VoteRegister {
questionId: string;
questionSlugs: string[];
}
const voteSlice = createSlice({
name: "vote",
initialState: {
votes: {},
},
reducers: {
registerVote: (
state: VoteSliceState,
action: PayloadAction<VoteRegister>,
) => {
state.votes[action.payload.questionId] = {};
action.payload.questionSlugs.forEach((value) => {
state.votes[action.payload.questionId][value] = null;
});
},
changeVote: (
state: VoteSliceState,
action: PayloadAction<VoteChange>,
) => {
const foundVote =
state.votes[action.payload.questionId][action.payload.optionId];
if (foundVote !== null) {
if (foundVote === 1 && action.payload.change <= 0) {
return;
}
if (
foundVote >=
Object.keys(state.votes[action.payload.questionId])
.length &&
action.payload.change >= 0
) {
state.votes[action.payload.questionId][
action.payload.optionId
] = null;
return;
}
state.votes[action.payload.questionId][
action.payload.optionId
] += action.payload.change;
} else {
if (action.payload.change <= 0) {
state.votes[action.payload.questionId][
action.payload.optionId
] = Object.keys(
state.votes[action.payload.questionId],
).length;
}
}
},
},
});
export const { registerVote, changeVote } = voteSlice.actions;
export default voteSlice.reducer;
|