You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.7 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. interface CountdownTimerProps {
  4. initialSeconds: number,
  5. onComplete?: Function
  6. }
  7. export interface CountdownTimerRef {
  8. handleStop: Function,
  9. handleStart: Function,
  10. handleReset: Function,
  11. isActive: boolean
  12. }
  13. const CountdownTimer = forwardRef<CountdownTimerRef, CountdownTimerProps>((props, ref) => {
  14. const { initialSeconds, onComplete } = props
  15. const { t } = useTranslation()
  16. const [seconds, setSeconds] = useState(initialSeconds);
  17. const [isActive, setIsActive] = useState(false);
  18. const [title, setTitle] = useState('Send verification code')
  19. useImperativeHandle(ref, () => ({
  20. handleStop,
  21. handleReset,
  22. handleStart,
  23. isActive
  24. }))
  25. const handleStop = () => {
  26. setIsActive(false);
  27. setTitle('Send verification code')
  28. };
  29. const handleStart = () => {
  30. if (isActive) return
  31. setSeconds(initialSeconds)
  32. setIsActive(true);
  33. };
  34. const handleReset = () => {
  35. setSeconds(initialSeconds);
  36. setIsActive(true);
  37. };
  38. useEffect(() => {
  39. let interval: any = null;
  40. if (isActive && seconds > 0) {
  41. interval = setInterval(() => {
  42. setSeconds(seconds => seconds - 1);
  43. }, 1000);
  44. } else {
  45. clearInterval(interval)
  46. seconds <= 0 && setTitle('Resend')
  47. setIsActive(false)
  48. // onComplete && onComplete(seconds)
  49. }
  50. return () => clearInterval(interval);
  51. }, [isActive, seconds, onComplete]);
  52. return (
  53. <div style={{ whiteSpace: 'pre-wrap' }}>{isActive ? <span className='fz-18 fw550'>{seconds}s</span> : t(title)}</div>
  54. );
  55. });
  56. export default CountdownTimer;