import { Button, Container, FormControl, FormErrorMessage, FormLabel, Heading, Input, Text, } from '@chakra-ui/react' import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router' import { SubmitHandler, useForm } from 'react-hook-form' import { useMutation } from 'react-query' import { ApiError, LoginService, NewPassword } from '../client' import { isLoggedIn } from '../hooks/useAuth' import useCustomToast from '../hooks/useCustomToast' interface NewPasswordForm extends NewPassword { confirm_password: string } export const Route = createFileRoute('/reset-password')({ component: ResetPassword, beforeLoad: async () => { if (isLoggedIn()) { throw redirect({ to: '/', }) } }, }) function ResetPassword() { const { register, handleSubmit, getValues, reset, formState: { errors }, } = useForm({ mode: 'onBlur', criteriaMode: 'all', defaultValues: { new_password: '', }, }) const showToast = useCustomToast() const navigate = useNavigate() const resetPassword = async (data: NewPassword) => { const token = new URLSearchParams(window.location.search).get('token') if (!token) return await LoginService.resetPassword({ requestBody: { new_password: data.new_password, token: token }, }) } const mutation = useMutation(resetPassword, { onSuccess: () => { showToast('Success!', 'Password updated.', 'success') reset() navigate({ to: '/login' }) }, onError: (err: ApiError) => { const errDetail = err.body?.detail showToast('Something went wrong.', `${errDetail}`, 'error') }, }) const onSubmit: SubmitHandler = async (data) => { mutation.mutate(data) } return ( Reset Password Please enter your new password and confirm it to reset your password. Set Password {errors.new_password && ( {errors.new_password.message} )} Confirm Password value === getValues().new_password || 'The passwords do not match', })} placeholder="Password" type="password" /> {errors.confirm_password && ( {errors.confirm_password.message} )} ) } export default ResetPassword