Home  >  Q&A  >  body text

Avoid resetting timeout on refresh in Reactjs

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 (
    <div>

      <h3>{count} / 3</h3>
      <button disabled={disable} onClick={handleDec}>
        Remaining Use
      </button>

    </div>
  )
}

export default Without
P粉285587590P粉285587590432 days ago533

reply all(2)I'll reply

  • P粉463811100

    P粉4638111002023-09-08 00:28:18

    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:

    import React, { useEffect, useState } from "react";
    
    function Without() {
      const [count, setCount] = useState(3);
      const [disable, setDisable] = useState(false);
    
      const handleDec = () => {
        if (count > 1) {
          setCount(count - 1);
        } else {
          setCount(0);
          setDisable(true);
          const timestamp = new Date().getTime(); // 获取当前时间戳
          localStorage.setItem("disabledTimestamp", timestamp);
        }
      };
    
      // 检查按钮被禁用后是否已经过了5秒
      useEffect(() => {
        const disabledTimestamp = localStorage.getItem("disabledTimestamp");
        if (disabledTimestamp) {
          const currentTime = new Date().getTime();
          const fiveSecondsInMillis = 5000;
          const difference = currentTime - parseInt(disabledTimestamp, 10);
    
          if (difference < fiveSecondsInMillis) {
            setDisable(true);
            const timeout = setTimeout(() => {
              setDisable(false);
              setCount(3);
              localStorage.removeItem("disabledTimestamp"); // 重新启用按钮后重置时间戳
            }, fiveSecondsInMillis - difference);
    
            return () => clearTimeout(timeout);
          } else {
            setDisable(false);
            localStorage.removeItem("disabledTimestamp"); // 如果超过5秒则重置时间戳
          }
        }
      }, [disable]);
    
      // LOCALSTORAGE
      useEffect(() => {
        const storedCount = localStorage.getItem("count");
        if (storedCount) {
          setCount(parseInt(storedCount));
        }
      }, []);
    
      return (
        <div>
          <h3>{count} / 3</h3>
          <button disabled={disable} onClick={handleDec}>
            剩余使用次数
          </button>
        </div>
      );
    }
    
    export default Without;

    reply
    0
  • P粉184747536

    P粉1847475362023-09-08 00:18:30

    You just need to set an extra if statement check for '0' to disable. You have stored the value correctly.

    //LOCALSTORAGE
      useEffect(() => {
        const storedCount = localStorage.getItem('count');
        console.log("storedcount: ", storedCount);
        if (storedCount) {
          setCount(parseInt(storedCount));
          if (storedCount === '0') {
            setDisable(true);
          }
        }
      }, []);

    reply
    0
  • Cancelreply