I'm learning react by making a battleship game. When the component loads, I create a new object (board) which I set as a state. Then I'd like to map the board itself, which is any array. However, react says cannot read property board of undefined. With console logging, I found out that at first when the page loads, playerBoard is an empty object, and only THEN sets it to the given object with setPlayerBoard. How could I avoid this?
App.js looks like this:
const GameControl = () => {
const [playerBoard, setPlayerBoard] = useState({})
//creating the board object when component mounts, setting it as a state
useEffect(() => {
const playerBoard = GameBoard('player');
setPlayerBoard({...playerBoard});
},[])
return (
<div className = 'board-container'>
<div className = "board player-board">
{ //mapping an array
playerBoard.boardInfo.board.map((cell, i) => {
return (
<div className = {`cell player-cell`key = {i}></div>
)
} )
}
</div>
</div>
)
}