There is a button that will be disabled after 3 clicks. When I refresh the page, the counter remains the same (1/3, 2/3 or 0/3). But I can't do the same with disabled buttons. I don't want to reset setTimeout. I hope it picks up where I left off.
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 () } export default Without{count} / 3
Don't rely on the setTimeOut function that sets the delay to 5000ms, consider using a timestamp. You can save the timestamp in localStorage and then compare with the current timestamp. If the difference is equal to or greater than 5000ms, the button is re-enabled. Here is the complete code and my implementation:
You just need to set an extra if statement check for '0' to disable. You have stored the value correctly.