Eugene Kliuchnikov
Eugene Kliuchnikov

Reputation: 61

React. How to decrease timer value in localstorage by one?

How to decrease timer value in localstorage by one? I used the useLocalStorage hook, but the value does not dynamically decrease by one. Thank you!

Timer:

const [timeLeft, setTimeLeft] = useLocalStorage('timer',  5 * 60)

const getPadTime = (time) => time.toString().padStart(2, '0')

const minutes = getPadTime(Math.floor(timeLeft / 60))
const seconds = getPadTime(timeLeft - minutes * 60)

useEffect(() => {
    const interval = setInterval(() => {
        setTimeLeft((timeLeft) => (timeLeft >= 1 ? timeLeft - 1 : setDisabled() ||  5 * 60))
    }, 1000)
    return () => clearInterval(interval) 
}, [])

Upvotes: 1

Views: 226

Answers (1)

Steffen Frank
Steffen Frank

Reputation: 1797

The use-local-storage hook you referred to does not support the setState(previousValue => nextValue) syntax.

The easiest way to fix this is to use a different implementation, e.g. this one: use-local-storage, used in gerrod 's comment

Upvotes: 1

Related Questions