There is a button that is disabled after 3 clicks. Counter is preserved (1/3 2/3 or 0/3) when I refresh the page. But I can’t do the same thing for disabled button. I don’t want to reset setTimeout. I want it to continue from the time it left.
import React, { useEffect, useState } from 'react'
function Without() {
//const [count, setCount] = useState(3);
const [count, _setCountValue] = useState(3);
const [disable, setDisable] = useState(false);
function setCount(value) {
localStorage.setItem('count', JSON.stringify(value))
return _setCountValue(value)
}
const handleDec = () => {
if (count > 1) {
setCount(count - 1);
} else {
setCount(0);
setDisable(true);
const timeout = setTimeout(() => {
setDisable(false);
setCount(3);
}, 5000);
return () => clearTimeout(timeout);
}
};
//LOCALSTORAGE
useEffect(() => {
const storedCount = localStorage.getItem('count');
if (storedCount) {
setCount(parseInt(storedCount));
}
}, []);
return (
<div>
<h3>{count} / 3</h3>
<button disabled={disable} onClick={handleDec}>
Remaining Use
</button>
</div>
)
}
export default Without
2
Answers
You just need to set an additional if statement check for ‘0’ for disabling. You’re storing the value properly.
Instead of relying on the setTimeOut function with a delay of 5000ms, consider using the timestamp. You can save the timestamp in your localStorage and later compare it with the current timestamp. If the difference is equal to or greater than 5000ms, then enable the button again. Here is the full code with my implementation: