From 58310afba4e89db6966fbf8f32cd4a44a52a6ca6 Mon Sep 17 00:00:00 2001 From: Joe Banks Date: Thu, 11 Jul 2024 02:23:51 +0100 Subject: Add new vote component and voting redux store --- src/slices/votes.ts | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/slices/votes.ts (limited to 'src/slices/votes.ts') diff --git a/src/slices/votes.ts b/src/slices/votes.ts new file mode 100644 index 0000000..87d84e8 --- /dev/null +++ b/src/slices/votes.ts @@ -0,0 +1,73 @@ +import { createSlice, PayloadAction } from "@reduxjs/toolkit"; + +export interface VoteSliceState { + votes: Record>; +} + +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, + ) => { + state.votes[action.payload.questionId] = {}; + action.payload.questionSlugs.forEach((value) => { + state.votes[action.payload.questionId][value] = null; + }); + }, + changeVote: ( + state: VoteSliceState, + action: PayloadAction, + ) => { + 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; -- cgit v1.2.3