2

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!

3
  • React state updates are not immediate ... Commented Jan 23, 2022 at 10:04
  • 1
    Does this answer your question? ReactJS state update and immediate access Commented Jan 23, 2022 at 10:05
  • Thanks I don't think so. I tried it out anyway and put the console statement into a callback function and it produced this error State updates from the useState() and useReducer() Hooks don't support the second callback Commented Jan 23, 2022 at 10:17

1 Answer 1

1

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)
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I thought the same. But its not so. When I console.log the new board value I see it behaving as expected. Also when I check dev tools Components state I can see that the old state is still there. I'm really stumped.
I found my problem. I have another effect that is acting on the cellstatuses. you are correct the code above is working, but I have a side effect elsewhere undoing my setStatuses.
gotcha.........

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.