Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React update state array in useEffect hook

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading