Every time I click the "increase" or "decrease" buttons for a certain player, I want the score to increase for that player only. However, right now when I click either of the buttons it increases both scores. I know it is probably something simple that I am completely overlooking, but any help is appreciated. Thank you in advance! Here is my code https://codesandbox.io/s/objective-curran-6ogn3?file=/src/App.js:0-2090:
import "./styles.css";
import {Component, useState} from 'react';
export default function App() {
const [count, setCount] = useState(0);
const [playerScore, setplayerScore] = useState([{
nameOne: 'Player 1'
}, {
nameTwo: 'Player 2'
}
]);
const increase = () => {
setCount(count 1);
setplayerScore(playerScore);
};
const decrease = () => {
setCount(count - 1);
setplayerScore(playerScore);
};
return (
<main>
{/* player 1*/}
<div>
{playerScore.map((player) => {
return (
<div>
<h2 className="name">{player.nameOne}</h2>
</div>
);
})}
</div>
<div>
<div className="score">{count}</div>
{/* increase button */}
<button onClick={increase}>
Increase
</button>
{/* decrease button */}
<button onClick={decrease}>
Decrease
</button>
</div>
{/* player 2 */}
<div>
{playerScore.map((player) => {
return (
<div>
<h2 className="name">{player.nameTwo}</h2>
</div>
);
})}
</div>
<div>
<div className="score">{count}</div>
<section>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</section>
</div>
</main>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
CodePudding user response:
I did this fork based on your code. https://codesandbox.io/s/cranky-hooks-q9ntu?file=/src/App.js
I have refactored some logic and added the functionality that I understand you want. Specially the increase/decrease logic.
The main error was that you were using same state for the entire array, so the value will always be the same for all the items.