Files
IDP-Frontend/components/ResendVerificationCode/ResendVerificationCode.tsx

60 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { FC, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button } from "@mantine/core";
import { setLastSendTime } from "@/lib/features/verification/verificationSlice";
import { RootState } from "@/lib/store";
import { MAX_COUNTDOWN } from "@/constants/verification";
const ResendVerificationCode: FC = () => {
const [countdown, setCountdown] = useState(0);
const dispatch = useDispatch();
const lastSendTime = useSelector(
(state: RootState) => state.verification.lastSendTime
);
useEffect(() => {
dispatch(setLastSendTime(Date.now()));
setCountdown(MAX_COUNTDOWN);
}, []);
useEffect(() => {
if (lastSendTime) {
const elapsed = Math.floor((Date.now() - lastSendTime) / 1000);
const remaining = Math.max(0, MAX_COUNTDOWN - elapsed);
setCountdown(remaining);
}
}, [lastSendTime]);
useEffect(() => {
if (countdown > 0) {
const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
return () => clearTimeout(timer);
}
}, [countdown]);
const sendCode = () => {
if (countdown > 0) return;
};
const handleResend = () => {
sendCode();
dispatch(setLastSendTime(Date.now()));
setCountdown(MAX_COUNTDOWN);
};
return (
<Button
variant={"outline"}
disabled={countdown > 0}
onClick={handleResend}>
{countdown > 0
? `Отправить код через ${countdown}с`
: "Отправить код"}
</Button>
);
};
export default ResendVerificationCode;