-
-
Save agustif/67853395781e0593c22bd1b83a791ad7 to your computer and use it in GitHub Desktop.
Next Router - DelayRedirect
This file contains 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 { useRouter } from 'next/router'; | |
import React, { useEffect, useState } from 'react'; | |
interface DelayProps { | |
delay: number; | |
to: string; | |
banner: boolean; | |
showCount: boolean; | |
} | |
export const DelayRedirect = ({ delay, to, banner, showCount }: DelayProps): JSX.Element => { | |
const router = useRouter() | |
const seconds = Number(delay.toString()[0]) | |
const [counter, setCounter] = React.useState(seconds); | |
const [timeToRedirect, setTimeToRedirect] = useState(false); | |
useEffect(() => { | |
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000); | |
}, [counter]); | |
useEffect(() => { | |
const timeout = setTimeout(() => router.push(to), delay); | |
return () => clearTimeout(timeout); | |
}, [delay]); | |
return banner ? <p>Serás redirigido a {to === '/' ? 'Inicio' : to} {showCount ? `en ${counter} segundos...` : 'en breve'}</p> : null | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment