Main TSX File
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];
};
To demonstrate the problem. I have created a codesandbox link: https://codesandbox.io/s/hdwqy?file=/src/App.tsx
How to recreate the problem:
- By default minValue is 1 and maxValue is 10
- set the minValue to 8 and maxValue 9 (click "Change min & max value" button in codesandbox)
- run the getRandomNumber() function.
Outputs: 8 or 9- works! (click "New random Number" button in codesandbox) - refresh the page and you will get the data stored in local storage min = 8, and max = 9
- run the getRandomNumber() function.
outputs 0 or 1- wrong outputs! (click "New random Number" button in codesandbox) - 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