#issue with getting the lowest value from time and rolls and storing it in the local storage

1 messages · Page 1 of 1 (latest)

deft fractal
#

The problem is that you are using setRecords(); inside one of your useEffect's, which listens to the die changes.

You only want to set the record when the game ends, not on every dice roll.
You also want to compare the value saved in localstorage with the incoming value before saving it. You only want to save the new value if it is actually better than the saved one.

balmy shale
# deft fractal The problem is that you are using `setRecords();` inside one of your `useEffect`...

That’s what I tried React.useEffect(()=>{
if (tenzies==false)
{setRecords()}
},[tenzies])

let storage=JSON.parse(localStorage.getItem('best rolls'));
let initVal=0
const [bestRolls,setBestRolls]=React.useState(storage?storage:initVal);
//const [bestTime,setBestTime]=React.useState(()=>JSON.parse(localStorage.getItem("best time")) || 0);

   function setRecords() {
      if (initVal==0) {
        initVal=final
      }
      else if (initVal>0){
          if (storage<initVal) {
            setBestRolls(rolls)
          } else {
            setBestRolls(storage)
          }
      }
  //if (!setBestTime|| time/10 <bestTime) {
  //  setBestRolls(bestTime)
  //   console.log(bestTime)
 // } 
 }
  React.useEffect(()=>
  { localStorage.setItem('best rolls',JSON.stringify(bestRolls))},
  [bestRolls])
  //React.useEffect(()=>
  // {localStorage.setItem('best time',JSON.stringify(bestTime))},
  //[bestTime])
deft fractal
# balmy shale That’s what I tried React.useEffect(()=>{ if (tenzies==false) {se...

You need to "somehow" decide when the game ends. This can be a variable which is true or false eg.:
const isGameOver = calculateGameOver(...)
(You don't really need a state for this)

Then I would recommend you to create a new useEffect() which will only listen to this variable. Inside the useEffect you need to branch based on the value.
If the game is over, you compare the saved data in localstorage with the new data, if the new data is better, you save it otherwise you do nothing.
You probably also want to stop the timer etc... so you can also do that in here but that means you probably want to add more dependency to the useEffect's dependency list
I the game is not over, you don't do anything.