Newer
Older

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { AxiosError } from 'axios';
import { registerUser } from '../../services/Register/Register';
import { useAuth } from '../../hooks/useAuth';

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
import './Register.scss';
import { userToDashboard } from '../../helpers/UserType';

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
export interface IRegisterForm {

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
name: string;
email: string;
password: string;
confirmPassword: string;

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
}
export function Register() {
const { giveAuth, updateUser } = useAuth();
const navigate = useNavigate();

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
const [error, setError] = useState('');
const { register, handleSubmit } = useForm<IRegisterForm>({mode: 'onChange'});

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
const onSubmit = async (formValue: IRegisterForm) => {

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
if (formValue.password.length < 7) {
setError('password length must be greater than 6 characters');
return;
}
if (formValue.password !== formValue.confirmPassword) {
setError('password and confirm password must match');
return;
}
setError('');
try {
const result = await registerUser(formValue);
giveAuth();
updateUser(result.data);
navigate(`/${userToDashboard(result.data)}`);
const errorMessage = (error as AxiosError).response?.data;
if (typeof errorMessage == 'string') {
setError(errorMessage);
} else {
setError('An unexpected error has occurred');
}

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
};
return (
<>
<div className='register'>
<form onSubmit={handleSubmit(onSubmit)}>
<div className='card register-card'>
<div className='form-group'>
<label>Full Name</label>
<input type='text' placeholder='Full name' {...register('name', { required: true })} />
</div>
<div className='form-group'>
<label>Email Address</label>
<input type='email' placeholder='Enter email' {...register('email', { required: true })} />
</div>
<div className='form-group'>
<label>Password</label>
<input type='password' placeholder='Enter password' {...register('password', { required: true })} />
</div>
<div className='form-group'>
<label>Confirm Password</label>
<input type='password' placeholder='Confirm password' {...register('confirmPassword', { required: true })} />
</div>
<div className='form-group'>
<label>Customer Type</label>
<select {...register('customerType', { required: true })}>
<option value="customer">Customer</option>
<option value="airline">Airline</option>
</select>
</div>

Cross, Liam (UG - Comp Sci & Elec Eng)
committed
<div className='form-group'>
<button type='submit'>Submit</button>
</div>
<div className='form-group'>
{error && <span>{error}</span>}
</div>
</div>
</form>
</div>
</>
);
}
export default Register;