skip to Main Content

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


  1. You just need to set an additional if statement check for ‘0’ for disabling. You’re storing the value properly.

      //LOCALSTORAGE
      useEffect(() => {
        const storedCount = localStorage.getItem('count');
        console.log("storedcount: ", storedCount);
        if (storedCount) {
          setCount(parseInt(storedCount));
          if (storedCount === '0') {
            setDisable(true);
          }
        }
      }, []);
    
    Login or Signup to reply.
  2. 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:

    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(); // Get the current timestamp
          localStorage.setItem("disabledTimestamp", timestamp);
        }
      };
    
      // Check if 5 seconds have passed since the button was disabled
      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"); // Reset the timestamp after re-enabling the button
            }, fiveSecondsInMillis - difference);
    
            return () => clearTimeout(timeout);
          } else {
            setDisable(false);
            localStorage.removeItem("disabledTimestamp"); // Reset the timestamp if more than 5 seconds have passed
          }
        }
      }, [disable]);
    
      // 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search