I am building a simple react board game that consists of rows and columns of tiles that player 1 and 2 can be on.
I store the current location of the players in a state object playerLocation. I store the current player (whose turn it is now) in currentPlayer state.
After a click on a tile, I try to move the current player there and update playerLocation state with the movePlayer function. However instead of updating the playerLocation state object it creates an undefined key on the object. So my suspicion is that I am trying to use the variable [currentPlayer.row] incorrectly .
Can someone help me why? How can I update the state object correctly?
const [playerLocation, setPlayerLocation] = useState({
1: {
row: 2,
column: 2,
},
2: {
row: 2,
column: 2,
},
});
const [currentPlayer, setCurrentPlayer] = useState(1);
// location param contains the row and column of the clicked tile
const movePlayer = (location) => {
setPlayerLocation({
...playerLocation,
[currentPlayer.row]: location.row,
[currentPlayer.column]: location.column,
});
}