Skip to content

Instantly share code, notes, and snippets.

@agustif
Forked from JT501/DelayRedirect.tsx
Created October 29, 2020 23:30
Show Gist options
  • Save agustif/67853395781e0593c22bd1b83a791ad7 to your computer and use it in GitHub Desktop.
Save agustif/67853395781e0593c22bd1b83a791ad7 to your computer and use it in GitHub Desktop.
Next Router - DelayRedirect
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