I have a simple gameboard where I am wanting to calculate a score based on "rounds" available for each player. In the past, I would just make new inputs for each round but technically I don't care about the rounds themselves just the player and score. So I would like for the score to be updated when a player changes a any input on their game by recalculating all the other rounds to sum the score.
my issue is coming in at the calculateScore section. My thought would be somehow getting the input values of all the inputs for that player's ID, clear the score and then recalculate the score based on those inputs. But obviously open to suggestions as I am newer to React.
Game.tsx
import React, { useState, useCallback } from "react";
export type Polly = {
id: Number
name: String
rounds: Number
score: Number
removeable: Boolean
}
const Game = () => {
const rounds: number = 2;
const [newPlayer, setNewPlayer] = useState('')
const [players, setPlayers] = useState([
{ id: 1, name: "Player1", rounds: rounds, score: 0, removeable: false },
{ id: 2, name: "Player2", rounds: rounds, score: 0, removeable: false },
]);
const handleCreate = (p: string) => {
const newPlayer = {
id: Date.now(),
name: p,
rounds: rounds,
score: 0,
removeable: true
};
setPlayers([...players, newPlayer])
}
const handleDelete = useCallback((playerId: number) => {
const newPlayers = players.filter((polly: Polly) => polly.id !== playerId)
setPlayers(newPlayers)
}, [players])
const calculateScore = (roundScore: string, id: number) => {
console.log('RoundScore: ' + roundScore + ' id ' + id)
const filterPlayer = players.filter((polly: Polly) => polly.id !== id)
}
return (
<>
add players:
<input type="text" value={newPlayer} onChange={(e) => setNewPlayer(e.target.value)}/>
<button type="button" onClick={() => handleCreate(newPlayer)}>Add Player</button>
{players.map((player: any) => (
<div key={player.id}>
<span>{player.name}</span>
{[...Array(player.rounds)].map((x, i) => (
<input type="number" key={i + 1} name={String(player.id)} onChange={(e) => calculateScore(e.target.value, player.id)}/>
))}
{player.removeable ? <button type="button" onClick={() => handleDelete(player.id)}>X</button>: null}
{player.score}
</div>
))}
</>
);
};
export default Game;