Created
March 8, 2024 14:32
-
-
Save lenivene/507139301b0f6477538499b866d90ea6 to your computer and use it in GitHub Desktop.
This function, named `useResentCodeTimer`, is a custom React hook that manages a countdown timer for a resend code functionality
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
interface ResentCodeTimerProps { | |
initialValue?: number; | |
} | |
export const useResentCodeTimer = ({ initialValue = 60 }: ResentCodeTimerProps) => { | |
const [resentCodeIn, setResentCodeIn] = useState(initialValue); | |
let startTime: Date | undefined; | |
useEffect(() => { | |
if (resentCodeIn > 0) { | |
startTime = new Date(); | |
} else { | |
startTime = undefined; | |
} | |
const intervalId = setInterval(() => { | |
if (startTime) { | |
const elapsed = Math.floor((new Date() - startTime) / 1000); | |
setResentCodeIn(Math.max(initialValue - elapsed, 0)); | |
if (elapsed >= initialValue) { | |
clearInterval(intervalId); | |
} | |
} | |
}, 100); | |
return () => { | |
clearInterval(intervalId); | |
}; | |
}, [resentCodeIn, initialValue]); | |
return resentCodeIn; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment