admin管理员组

文章数量:1290424

Problem:- I have made a modal in which i am doing Mobile number verification. I want OTP timer to get started on clicking the Send OTP button but it is not happenning.

I have used useeffect() to create timer but in that way, timer is starting to run on page load but i only want timer to get started on clicking the Send OTP button click. How can i do that?

I am pasting the Code sandbox link for your reference. Please guide me.

Code:-

Problem:- I have made a modal in which i am doing Mobile number verification. I want OTP timer to get started on clicking the Send OTP button but it is not happenning.

I have used useeffect() to create timer but in that way, timer is starting to run on page load but i only want timer to get started on clicking the Send OTP button click. How can i do that?

I am pasting the Code sandbox link for your reference. Please guide me.

Code:- https://codesandbox.io/s/goofy-hawking-wd1ze9

Share Improve this question asked Jun 4, 2022 at 9:26 user19262822user19262822 2
  • Maybe by using an event handler? reactjs/docs/handling-events.html – derpirscher Commented Jun 4, 2022 at 9:28
  • Sir, can you please guide me. – user19262822 Commented Jun 4, 2022 at 11:40
Add a ment  | 

3 Answers 3

Reset to default 4
import React, { useEffect, useState } from "react";

function App() {
  const [otp, setOtp] = useState("");
  const [minutes, setMinutes] = useState(0);
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      if (seconds > 0) {
        setSeconds(seconds - 1);
      }

      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(interval);
        } else {
          setSeconds(59);
          setMinutes(minutes - 1);
        }
      }
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  });

  const sendOTP = () => {
    setMinutes(2);
    setSeconds(59);
  };
  const resendOTP = () => {
    setMinutes(2);
    setSeconds(59);
  };

  return (
    <div className="container">
      <div className="card">

        <input
          placeholder="Enter OTP"
          value={otp}
          onChange={({ target }) => {
            setOtp(target.value);
          }}
        />
        <button onClick={sendOTP}>Generate Otp </button>
        <div className="countdown-text">
          {seconds > 0 || minutes > 0 ? (
            <p>
              Time Remaining: {minutes < 10 ? `0${minutes}` : minutes}:
              {seconds < 10 ? `0${seconds}` : seconds}
            </p>
          ) : (
            <p>Didn't recieve code?</p>
          )}

          <button
            disabled={seconds > 0 || minutes > 0}
            style={{
              color: seconds > 0 || minutes > 0 ? "#DFE3E8" : "#FF5630"
            }}
            onClick={resendOTP}
          >
            Resend OTP
          </button>
        </div>

        <button class Name = "submit">SUBMIT</button>
      </div>
    </div>
  );
}

export default App;

Countdown Start with button click event in ReactJs:

import React from 'react'
import { useState, useEffect } from 'react';

const Timer = (props:any) => {
    const {initialMinute = 0,initialSeconds = 0} = props;
    const [ minutes, setMinutes ] = useState(initialMinute);
    const [seconds, setSeconds ] =  useState(initialSeconds);
    useEffect(()=>{
    let myInterval = setInterval(() => {
            if (seconds > 0) {
                setSeconds(seconds - 1);
            }
            if (seconds === 0) {
                if (minutes === 0) {
                    clearInterval(myInterval)
                } else {
                    setMinutes(minutes - 1);
                    setSeconds(59);
                }
            } 
        }, 1000)
        return ()=> {
            clearInterval(myInterval);
          };
    });

    return (
        <div>
        { minutes === 0 && seconds === 0
            ? null
            : <h1> {minutes}:{seconds < 10 ?  `0${seconds}` : seconds}</h1> 
        }
        </div>
    )
}

export default Timer;

Simply use this snippet, As it will also help to memoize the timeout callback.

const [timer, setTimer] = useState(60);    
const timeOutCallback = useCallback(() => setTimer(currTimer => currTimer - 1), []);

useEffect(() => {
  timer > 0 && setTimeout(timeOutCallback, 1000);
}, [timer, timeOutCallback]);

console.log(timer);

const resetTimer = function () {
  if (!timer) {
    setTimer(60);
  }
};

In your JSX

<Text style={styles.textLogin} onPress={resetTimer}>Resend OTP ({timer})</Text>

Hope this will help you or somebody else.

Happy Coding!

本文标签: javascriptHow to set OTP timer on button click in react JSStack Overflow