I'm trying to set of my useState to id of clicked element when user clicked it. But it shows empty string when i'm trying to console it and dispatch it. So, it feels like it didn't successfully set the state. and I don't know why.
This is the snippet code of it:
const Game = () => {
const [gameMode, setGameMode] = useState('');
const dispatch = useDispatch();
return (
<div id='computer' className='to-play-computer' onClick={(e) => {
setGameMode(e.currentTarget.id); // THIS DOESN'T CHANGE THE gameMode state to id 'computer'
// WAIT UNTIL THIS FUNCTION DONE
handleClickGameMode(e)
.then(() => {
console.log(gameMode); // IT WILL CONSOLE EMPTY STRING
dispatch(isGamePlay(gameMode));
})
}}>
<div className='icon-gameplay'>
<FaRobot />
</div>
<p className='description-gameplay'>
vs Computer
</p>
</div>
)
}
But if assigned it to simple variable, like this:
let gameMode = ""; // This will store the id of clicked element
const dispatch = useDispatch();
return (
<div id='computer' className='to-play-computer' onClick={(e) => {
gameMode = e.currentTarget.id // changed
// WAIT UNTIL THIS FUNCTION DONE
handleClickGameMode(e)
.then(() => {
console.log(gameMode); // IT WILL SUCCESSFULY CONSOLE 'COMPUTER'
dispatch(isGamePlay(gameMode));
})
}}>
<div className='icon-gameplay'>
<FaRobot />
</div>
<p className='description-gameplay'>
vs Computer
</p>
</div>
)
So, how to make this successful using useState? And maybe you can explain me why did this happened? Because in other projects I've created, like setState from onChange input form, it didn't create this problem. Thank you.
useEffect(() => {
dispatch(isGamePlay(gameMode));
}, [gameMode]);