52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
import { BaseForm } from './base-form';
|
|
import { ButtonLoading, ButtonLogin } from './buttons';
|
|
import { ERROR_INVALID_CREDENTIALS, ERROR_SERVER } from './errors';
|
|
import type { FormData } from './types';
|
|
import { redirect } from '@/components/Form/utils';
|
|
import { FormStateContext } from '@/context/form-state';
|
|
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, user: undefined },
|
|
type: 'set-error',
|
|
})
|
|
);
|
|
}
|
|
|
|
if (step === 'login' && user) {
|
|
handleRefreshToken();
|
|
|
|
return <ButtonLoading />;
|
|
}
|
|
|
|
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)}>
|
|
<ButtonLogin />
|
|
</BaseForm>
|
|
);
|
|
}
|