samedi 13 mars 2021

Ionic React - randomizer min max gives wrong values even tho min value and max value is set

My function looks like this:

Randomizer

  const [minNumber, setMinNumber] = useLocalStorage('minRange', 1);
  const [maxNumber, setMaxNumber] = useLocalStorage('maxRange', 10);

...

  const getRandomNumber = () => {
    //Return a random number between minNumber and maxNumber:
    console.log("min: " + minNumber + " max: " + maxNumber)
    let randomNr = Math.floor(Math.random() * (maxNumber - minNumber + 1) + minNumber);
    setRandomNumber(randomNr);
  }

Local Storage hook:

import { useState } from 'react';

export function useLocalStorage(key, defaultValue) {
    const getInitialValue = () => localStorage.getItem(key) ?? defaultValue;
    const [value, setValue] = useState(getInitialValue);
    const setAndStoreValue = (newValue) => {
        if (newValue !== '') {
            setValue(newValue);
            localStorage.setItem(key, newValue)
        }
    }
    return [value, setAndStoreValue];
};

How to recreate the problem:

  • By default minValue is 1 and maxValue is 10
  • set the minValue to 8 and maxValue 9
  • run the getRandomNumber() function. (random nr outputs 8 or 9 - works!)
  • refresh and you will get the data stored in local storage min = 8, and max = 9
  • run the getRandomNumber() function. (random nr outputs 0 or 1 - wrong outputs!)
  • The problem is since the difference between min and max is 2, it gives 0 and 1. If min was 8 and max was 10 then it will output 0, 1, or 2.

I can't seem to figure out why this is happening, since it works fine if I set the min and max again and rerun the random function. I would also like to mention that in both cases the console.log outputs min: 8 max: 9, Therefore it seems local storage is loading the value correctly. It is quite odd.




Aucun commentaire:

Enregistrer un commentaire