(Updated code anyone have another logic then please share)
I’m trying to set state for a team but I’m not able to do it.
I want to set individual state for each team without using any advance logic.
I tried many thing in code but nothing works. The state should be change for the team who’s button is clicked and others remains same.
const PointsTable = () => {
const [teams,setTeam] = useState({
CSK: { matchesPlayed: 0, wins: 0, loses: 0, points: 0 },
MI: { matchesPlayed: 0, wins: 0, loses: 0, points: 0 },
KKR: { matchesPlayed: 0, wins: 0, loses: 0, points: 0 },
GT: { matchesPlayed: 0, wins: 0, loses: 0, points: 0 }
});
function input(team) {
var teamName = team;
var matches = prompt("Enter total matches played: ");
var win = prompt("Enter total matches won: ");
var lose = matches - win;
var point = win * 2;
teams[teamName].matchesPlayed = matches;
teams[teamName].wins = win;
teams[teamName].loses = lose;
teams[teamName].points = point;
setTeam({ ...teams });
}
return (
<div>
<h2>IPL Points Table</h2>
<table border={1} cellPadding={20} cellSpacing={0}>
<thead>
<tr>
<th></th>
<th>Total Matches Played</th>
<th>Wins</th>
<th>Loses</th>
<th>Points</th>
</tr>
</thead>
<tbody>
<tr>
<td>CSK</td>
<td>{teams.CSK.matchesPlayed}</td>
<td>{teams.CSK.wins}</td>
<td>{teams.CSK.loses}</td>
<td>{teams.CSK.points}</td>
<td><button value='CSK' onClick={() => input("CSK")}>CSK</button></td>
</tr>
<tr>
<td>MI</td>
<td>{teams.MI.matchesPlayed}</td>
<td>{teams.MI.wins}</td>
<td>{teams.MI.loses}</td>
<td>{teams.MI.points}</td>
<td><button value='MI' onClick={() => input("MI")}>MI</button></td>
</tr>
<tr>
<td>KKR</td>
<td>{teams.KKR.matchesPlayed}</td>
<td>{teams.KKR.wins}</td>
<td>{teams.KKR.loses}</td>
<td>{teams.KKR.points}</td>
<td><button value='KKR' onClick={() => input("KKR")}>KKR</button></td>
</tr>
<tr>
<td>GT</td>
<td>{teams.GT.matchesPlayed}</td>
<td>{teams.GT.wins}</td>
<td>{teams.GT.loses}</td>
<td>{teams.GT.points}</td>
<td><button value='GT' onClick={() => input("GT")}>GT</button></td>
</tr>
</tbody>
</table>
</div>
);
};
export default PointsTable;
I’m trying to set state for a team but I’m not able to do it.
3
Answers
Your useState() hook usage is wrong.
You should initialise it like this:
Then you use setTeams to change the value of teams.
Your usage of
useState
is incorrect.useState
returns an array containing a state object and a "setter method" that updates the state object. This allows for updating a state object through the React rendering lifecycle. You cannot update a state variable directly, as you have tried.Instead you should use the setter method, something like this:
The JSX HTML would look like this:
Additionally, I wouldn’t use
prompt
here to update the values, but instead I’d create some React component or HTML input that handles the new data, perhaps as Form Fields or within a Modal.Here is the entire working code with some improvements. I believe the other comments have already explained the issues with this.