1

Hi I am trying to update a state in Reactjs just after popluating an array , but everytime it comes as an empty array. I guess this is due to async behaviour of setState, but I am unable to put my head as how to solve it.

Any help is appreciated

const [game, setgame] = useState({ row: 6, column: 6, w: 100, x: '', y: '', arr: [], placedWordsX: [], boardArray: [] })
const grid=16;

useEffect(() => {
    start();
   }, [])

function start() {

    let newGameArr = []
    for (let i = 0; i < grid; i++) {
            newGameArr[i] = "-";
    }
    setgame({...game, arr:newGameArr})      
    console.log(game)
    console.log(game.array) //always coming empty
}

manish singh
  • 87
  • 1
  • 13
  • Does this answer your question? [Console.log() after setState() doesn't return the updated state](https://stackoverflow.com/questions/54713510/console-log-after-setstate-doesnt-return-the-updated-state) – 0stone0 Mar 23 '23 at 10:25
  • you should try this start function behind some button click. It would solve you problem. – Asma Mar 23 '23 at 10:32
  • Well you should probably use `useRef` it would work, but you can also change your setGame to `setGame(prevGame => ({...prevGame, arr: newGameArr}))` – Fried noodles Mar 23 '23 at 10:42
  • @Friednoodles setGame(prevGame => ({...prevGame, arr: newGameArr})) ,I have tried this but this doesn't work. useRef I don't think is right for me. – manish singh Mar 23 '23 at 11:01
  • @Asma I need on loadm not on some button click – manish singh Mar 23 '23 at 11:03

0 Answers0