63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
import styles from './Form.module.scss';
|
||
import { publicRuntimeConfig } from '@/config/runtime';
|
||
import axios from 'axios';
|
||
import { useState } from 'react';
|
||
import { useForm } from 'react-hook-form';
|
||
|
||
const { APP_BASE_PATH } = publicRuntimeConfig;
|
||
|
||
type FormData = {
|
||
readonly login: string;
|
||
readonly password: string;
|
||
};
|
||
|
||
function handleDefaultLogin(data: FormData) {
|
||
const redirectUrl =
|
||
(window.location.pathname.replace(APP_BASE_PATH, '') || '/') + (window.location.search || '');
|
||
|
||
return axios.post('/login', data).then(() => {
|
||
window.location.replace(redirectUrl);
|
||
});
|
||
}
|
||
|
||
type LoginFormProps = {
|
||
readonly onLogin: (data: FormData) => Promise<void>;
|
||
};
|
||
|
||
function LoginForm({ onLogin }: LoginFormProps) {
|
||
const [hasError, setHasError] = useState(false);
|
||
const { handleSubmit, register } = useForm<FormData>();
|
||
|
||
return (
|
||
<form
|
||
className={styles.form}
|
||
onSubmit={handleSubmit((data) => {
|
||
onLogin(data).catch(() => setHasError(true));
|
||
})}
|
||
>
|
||
<input
|
||
type="text"
|
||
placeholder="Логин"
|
||
required
|
||
autoComplete="on"
|
||
{...register('login', { required: true })}
|
||
/>
|
||
<input
|
||
type="password"
|
||
placeholder="Пароль"
|
||
required
|
||
autoComplete="on"
|
||
{...register('password', { required: true })}
|
||
/>
|
||
{hasError ? <span className="error">Неверный логин или пароль</span> : null}
|
||
<button className={styles['button-submit']} type="submit">
|
||
Войти
|
||
</button>
|
||
</form>
|
||
);
|
||
}
|
||
|
||
export function Form() {
|
||
return <LoginForm onLogin={handleDefaultLogin} />;
|
||
}
|