I'm pretty good in Vue and React raising just a lot questions to me.
I'm doing variation of tic-tac-toe game just to see how React works. I wrote it and it works just fine but with delay 1 move and I don't know why. Here is a part of a code
function App() {
let [board, setBoard] = useState([
null, null, null,
null, null, null,
null, null, null
]);
let [turn, setTurn] = useState('X');
let checkWinner = () => {
console.log(board, 'board in checkWinner'); // board is not updated
if((board[0] === board[1] && board[1] === board[2] && board[1] !== null) ||
(board[3] === board[4] && board[4] === board[5] && board[4] !== null) ||
(board[6] === board[7] && board[7] === board[8] && board[7] !== null)){
console.log("We have a winner")
setBoard(Array(9).fill(null))
}
}
let cellClicked = (i) => {
let newBoard = [...board];
newBoard[i] = turn;
setTurn(turn === 'X' || !turn ? 'O' : 'X');
setBoard(newBoard);
console.log(newBoard); // board is updated
checkWinner();
}
.
.
.
that's not a whole code, but a part where I have an issue. Function cellClicked() is triggered when in child component was pressed button. Then it sets a new board and in console.log is clearly updated as it expected, then by the end of this function triggers checkWinner and that is where I have problem. In console.log it shows me that board wasn't updated. When I press next times - first console shows everything good, but second console shows with 1 step delay. Why is that ? Thank you! async - await didn't help