super-fit-web-app / src / pages / verify-email.tsx
verify-email.tsx
Raw
import { useState, useEffect } from 'react'
import { Box, Paper, Typography, Button, CircularProgress } from '@mui/material'
import { useCustomTheme } from '@/themes/useCustomTheme'
import Link from 'next/link';
import { useRouter } from 'next/router';
import { trpc } from '@/utils/trpc';
import { useUserContext } from '@/context/UserContext';

const VerifyEmail = () => {
  const router = useRouter();
  const { token } = router.query;
  const [resend, setResend] = useState(false)
  const theme = useCustomTheme();
  const { userData, userSessionDataLoading } = useUserContext();

  const { mutateAsync: validateToken, isLoading, isError, error } = trpc.auth.verifyEmail.useMutation()

  useEffect(() => {
    if (!userSessionDataLoading && userData.emailVerified !== null) {
      router.push('/dashboard')
    }

    const fetchData = async () => {
      if (token) {
        const data = await validateToken({ token: token as string})
        
        if (data.validated) {
          router.push('/dashboard')
        }
      }
    }

    fetchData()
  }, [token, userSessionDataLoading])
  

  const resendEmail = () => {
    setResend(true)
    setTimeout(() => {
      setResend(false)
    }, 60000);
  }
  return (
    <Box 
      sx={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        px: theme.customProperties.sectionPaddingX
      }}
    >
      <Paper
        sx={{
          p: { xs: 2, md: 3, lg: 4 },
          width: '100%',
          maxWidth: '400px',
        }}
      >
        {!token && (
          <>
            <Typography variant='h3'>Verify Your Email</Typography>
            <Typography variant='body1'>Please check your email and click the verification link.</Typography>
            <Typography variant='body1'>Make sure to check your spam folder if you can&apos;t find it.</Typography>
            <Typography variant='body1'>If you think you have set the wrong email, please contact support@superfit.com</Typography>
            <Button onClick={resendEmail} disabled={resend}>Resend Verification Email?</Button>
          </>
        )}
        {token && (
          <>
            <Typography variant='h3'>Verifying Your Email</Typography>
            {isLoading && (
              <CircularProgress />
            )}
            {isError && (
              <Typography color={'red'}>Error: {error.message}</Typography>
            )}
          </>
        )}
      </Paper>
    </Box>
  )
}

export default VerifyEmail