I've read all the questions and answers about setting State on an array in React but none seem to fix my issue.
I initialise my arrays like this:
const initialStates = {cellStatuses: () =>Array(6).fill(Array(5).fill(status.unguessed)),
}
const [dailyCellStatuses, setDailyCellStatuses] = useLocalStorage('dailyCellStatuses', initialStates.cellStatuses)
const [cellStatuses, setCellStatuses] = useState(initialStates.cellStatuses)
and then later I use an effect to mimic componentDidMount and in that effect I check if the cellStatuses need to be updated
useEffect (() => {
if (gameMode && playedAlreadyToday(lastPlayedDate)) {
setBoard(dailyBoard)
setCellStatuses(dailyCellStatuses)
console.log(cellStatuses, 'cell statuses')
} else {
setBoard(initialStates.board)
}
The console always logs the old state it never updates with the new dailyCellStatuses that I am trying to set.
I have tried cloning the dailyCellStatuses [...dailyCellStatuses]
I have tried calling a function in the setter
I'm really stuck. Help!
your state is updating fine, your issue is you are console logging the value in the same render cycle,
Console log the value outside useEffect or you can do this
if (gameMode && playedAlreadyToday(lastPlayedDate)) {
setBoard(dailyBoard)
setCellStatuses(dailyCellStatuses)
console.log(dailyCellStatuses, 'cell statuses')
} else {
setBoard(initialStates.board)
}