From 142129a37656c00cbb828ed8eb8d0ec1bb159d7d Mon Sep 17 00:00:00 2001 From: djmil Date: Sat, 28 Oct 2023 12:25:50 +0200 Subject: [PATCH] front: AppCtx: better update function --- webapp/src/components/Game/NewGame.jsx | 8 ++--- webapp/src/context/app/reducer.js | 41 +++++++++++--------------- 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/webapp/src/components/Game/NewGame.jsx b/webapp/src/components/Game/NewGame.jsx index 9ed3a5a..fcf5f89 100644 --- a/webapp/src/components/Game/NewGame.jsx +++ b/webapp/src/components/Game/NewGame.jsx @@ -24,17 +24,17 @@ export default function NewGame() { : [] const whiteOptions = Array(nameOptions) - whiteOptions.push() + whiteOptions.push() const blackOptions = Array(nameOptions) - blackOptions.push() + blackOptions.push() const setWhitePlayer = (name) => { - dispatchCtx({ component: "new-game", whitePlayer: name }) + dispatchCtx({ update: "newGame", whitePlayer: name }) } const setBlackPlayer = (name) => { - dispatchCtx({ component: "new-game", blackPlayer: name }) + dispatchCtx({ update: "newGame", blackPlayer: name }) } return ( diff --git a/webapp/src/context/app/reducer.js b/webapp/src/context/app/reducer.js index 287af2e..b68ecc6 100644 --- a/webapp/src/context/app/reducer.js +++ b/webapp/src/context/app/reducer.js @@ -1,12 +1,12 @@ export const reducer = (state, action) => { - switch (action.component) { + switch (action.update) { case "game-selector": return GameSelector_update(state, action) - case "new-game": - return NewGame_update(state, action) + case "newGame": + return updateNewGame(state, action) default: console.warn("Unknown action.component", action.component) @@ -62,26 +62,21 @@ function GameSelector_update(state, action) { console.warn(action.component, "- bad property") } -function NewGame_update(state, action) { - if (Object.hasOwn(action, 'whitePlayer')) { - return { - ...state, - newGame: { - ...state.newGame, - whitePlayer: action.whitePlayer - } - } - } +function updateNewGame(state, action) { + const newGame = {...state.newGame} - if (Object.hasOwn(action, 'blackPlayer')) { - return { - ...state, - newGame: { - ...state.newGame, - blackPlayer: action.blackPlayer - } + Object.keys(action) + .slice(1) // skip 'update' property + .forEach(actionKey => { + if (Object.hasOwn(newGame, actionKey)) { + newGame[actionKey] = action[actionKey] + } else { + console.warn("NewGame update: bad action property\n", actionKey + ":", action[actionKey]) } - } + }) - console.warn(action.component, "- bad property") -} \ No newline at end of file + return { + ...state, + newGame + } +}