I am relative new to ReactJS and I have some problems with setState.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './index.js';
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
xNextPlayer: true
};
}
render() {
return (
<button
className="square"
onClick={ async () => {
console.log(this.state.xNextPlayer);
if(this.state.xNextPlayer === true) {
this.setState({value: 'X'});
} else {
this.setState({value: 'O'});
}
await this.setState({xNextPlayer: !this.state.xNextPlayer});
console.log(this.state.xNextPlayer);
}}
>
{this.state.value}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
**strong text**
The problem now is that xNextPlayer is not updated correctly. When I first click, xNextPlayer is true as it should. Then I want to set it to false. It does this correctly and console logs false. But when I click again, it is again set back to true. The first console log then is true, the second false.
But I want to store the value and be false.
Has anybody a solution?