I am trying to initialize useState hook with a class object then trying to update it based on a click eventListner but it is not updating more than one time.
function App() {
useEffect(() => {
const func = (e) => {
console.log('click')
handleKeyPress(10, 0)
}
document.addEventListener('click', func)
return () => document.removeEventListener('click', func)
}, [])
console.log('BEGIN')
const [player, setPlayer] = useState({
position: { x: 100, y: 100 },
direction: 'right',
})
console.log(player.position)
const handleKeyPress = (xChange, yChange) => {
const newX = player.position.x + xChange
const newY = player.position.y + yChange
let newDirection = player.direction
if (xChange > 0) {
newDirection = 'right'
}
if (xChange < 0) {
newDirection = 'left'
}
console.log('------->', player.position)
setPlayer((prev) => ({
...prev,
direction: newDirection,
position: { x: newX, y: newY },
}))
}
return (
<GameContainer className="game-container">
<Character positionx={player.position.x} positiony={player.position.y} />
</GameContainer>
)
}
export default App
console log can be seen below ->
as you can see the results it is not updating the x value of player state with every click also note that the string "BEGIN" is printing repeatedly with each click that means I think the render function is reinitiallizing the useState again and again.
