Build a One-Time Password Generator - 10, 11, and 14

Hi,
I’m totally stucked, not passing 10, 11, and 14 for this lab.
It works, when I click, i got the good results, but impossible to pass these steps.
If someone could give me a hint please :slight_smile:
thanks !

const { useState, useEffect, useRef } = React;

// Main component container
export function OTPGenerator() {
  const buttonRef = useRef(null);
  const [otp, setOtp] = useState('');
  const [disabled, setDisabled] = useState(false);
  const [showTimer, setShowTimer] = useState(false);
  const [timer, setTimer] = useState(5);

  // function to generate random 6 digits OTP
  function randomOtp() {
      return String(Math.floor(Math.random() * 1000000)).padStart(6, '0');  
    }

  function handleClick() {
    setTimer(5);
    setOtp(randomOtp());
    setShowTimer(true);
    setDisabled(true);

    setTimeout(() => {
      setOtp('');
      setDisabled(false);
    }, 5000)
  }

    return (
    <div className="container">
      <h1 id="otp-title">OTP Generator</h1>
      <h2 id="otp-display">{otp ? otp : `Click 'Generate OTP' to get a code`}</h2>
      {showTimer && <Counter timer={timer} setTimer={setTimer}/>}
      <button 
        ref={buttonRef}
        id="generate-otp-button"
        onClick={handleClick}
        disabled={disabled}>
      Generate OTP
      </button>
    </div>
  )
}

// function to have a counter
function Counter({timer, setTimer}) {

  useEffect(() => {
    if (timer === 0) return; // stop si timer à 0

    const intervalId = setInterval(() => {
      setTimer(prev => prev - 1);
    }, 1000);

    return () => clearInterval(intervalId);
  }, [timer]);

  return (timer === 0) ? <p id="otp-timer">OTP expired. Click the button to generate a new OTP</p> : <p id="otp-timer">OTP will disappear in: {timer} seconds</p>;
}

please share the link to the project

here it is : https://www.freecodecamp.org/learn/full-stack-developer/#lab-one-time-password-generator

Hi @Kiknjom

The timer does not reach 0.

Happy coding

hi,
with a console.log, i see what you mean. But don’t understand how i could change this. I set up the count stop when timer === 0, and if i try -1, it 's not stopping correctly :confused:

I passed the Lab.
Looks like it was just a missing “.” at the end of Expires…
I also change (timer - 1) for (prev => prev -1) in the setInterval of Counter.
Thanks for the help :slight_smile:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.