60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
import { BaseForm } from './base-form';
|
||
import { ERROR_INVALID_CREDENTIALS, ERROR_SERVER } from './errors';
|
||
import styles from './Form.module.scss';
|
||
import type { FormData } from './types';
|
||
import { FormStateContext } from '@/context/form-state';
|
||
import { redirect } from '@/utils/router';
|
||
import axios from 'axios';
|
||
import { useContext } from 'react';
|
||
|
||
export function DefaultForm() {
|
||
const {
|
||
dispatch,
|
||
state: { step, user },
|
||
} = useContext(FormStateContext);
|
||
|
||
function handleRefreshToken() {
|
||
axios
|
||
.get('/refresh-token')
|
||
.then(() => redirect())
|
||
.catch(() =>
|
||
dispatch({
|
||
payload: { error: ERROR_SERVER },
|
||
type: 'set-error',
|
||
})
|
||
);
|
||
}
|
||
|
||
if (step === 'login' && user) {
|
||
return (
|
||
<button
|
||
className={styles['button-submit']}
|
||
type="submit"
|
||
onClick={() => handleRefreshToken()}
|
||
>
|
||
Продолжить как <b>{user?.displayName || user.username}</b>
|
||
</button>
|
||
);
|
||
}
|
||
|
||
function handleLogin(data: FormData) {
|
||
return axios
|
||
.post('/login', data)
|
||
.then(() => redirect())
|
||
.catch(() =>
|
||
dispatch({
|
||
payload: { error: ERROR_INVALID_CREDENTIALS },
|
||
type: 'set-error',
|
||
})
|
||
);
|
||
}
|
||
|
||
return (
|
||
<BaseForm onSubmit={(data) => handleLogin(data)}>
|
||
<button className={styles['button-submit']} type="submit">
|
||
Войти
|
||
</button>
|
||
</BaseForm>
|
||
);
|
||
}
|