I am trying to make a simple counter app using reactjs and typescript. I am trying to store the count value in localstorage so that after reload I get the previous value and start count from there. But the problem is localstorage is always giving me 1 less value. For example my count progress was 30 but after refresh I get 29 from local storage. Seems like the count value is not updating on first click but updating from second click. What's wrong in my code?
const Counter = () => {
const [counter, setCounter] = useState<number>(0);
const [history, setHistory] = useState<number>(0);
useEffect(() => {
const previousCount: number = JSON.parse(localStorage.getItem('counter') || '{}');
setCounter(previousCount);
setHistory(previousCount);
}, [])
const increaseCount = () => {
setCounter(prevCount => prevCount + 1);
localStorage.counter = counter;
}
const decreaseCount = () => {
setCounter(prevCount => prevCount - 1);
localStorage.counter = counter;
}
const resetCount = () => {
setCounter(0)
localStorage.counter = counter;
}