0

I assume this is because of a delay in updating State. It's a memory game, every time the game gets over the score gets updated in the array and the array gets stored in the local storage

Following is the code

const gameOver = () => {
    //console.log(score) // shows the 
    setTopScore([...topScore, score]);
    updateLocalStorage()              
}
console.log(topScore) //shows the updated array

const updateLocalStorage = () => {
    let stringifyTopScore = JSON.stringify(topScore) 
    localStorage.setItem('gameTopScore', stringifyTopScore) //the array is not updated, shows an empty array in the localstorage on the first execution. On the second run of the fn, first value gets updated in the array and so on which creates error in highest score calculation.
    highScoreFn();
    setScore(0)
}```

I gave local storage in a separate function thinking there is a delay in updating the array, i think i haven't got it correctly, yet. What can i do here to see the updated array immediately in local storage.

codejs
  • 141
  • 1
  • 10

1 Answers1

3

Simple use useEffect, below is an example:

useEffect(() => {
    updateLocalStorage();
}, [topScore]);

It'll always called whenever state topscore updated

Piyush Rana
  • 631
  • 5
  • 8