0

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;
    }
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Shakil Ahmed
  • 39
  • 1
  • 5

2 Answers2

0

You have to set the localStorage by using setItemmethod

    const increaseCount = () => {
        setCounter(prevCount => prevCount + 1);
        localStorage.setItem("counter", counter + 1); // we know to increment by one
    }
    const decreaseCount = () => {
        setCounter(prevCount => prevCount - 1);
        localStorage.setItem("counter", counter - 1); // we know to decrement by one
    }
    const resetCount = () => {
        setCounter(0)
        localStorage.setItem("counter",0)
    }
  • As the counter value is not updated yet until next render, you will see the old value of counter ...
KcH
  • 3,302
  • 3
  • 21
  • 46
  • That works well and I tried this already. But I thought this is not the actual way to do it. Is there any other way? – Shakil Ahmed Oct 17 '22 at 05:40
  • you can use `useEffect` with `counter` as dependency and set it accordingly .. like the one in above answer ... – KcH Oct 17 '22 at 06:22
  • It works but when I reload the page the counter value in localstorage becomes 0 instead of the value where I left off. – Shakil Ahmed Oct 17 '22 at 06:25
  • change `const [counter, setCounter] = useState(0)` to `const [counter, setCounter] = useState(localStorage.getItem("counter"))` – KcH Oct 17 '22 at 06:32
0

you problem is in setvalue because it is callback so when you set value using setValue you did not get the current value:

    setCounter(prevCount => prevCount - 1); // couter value did not update yet 
    localStorage.counter = counter; // that why you get previous value

you can use useEffect like this:

useEffect(() => {
    if(counter) // check valid in you case
    {
      localStorage.counter = counter;
    }
}, [counter])