Evo.Auth/apps/web/components/Form/default-form.tsx
vchikalkin 20c0391e81 web: auto refresh token
reuse buttons in default & telegram forms
2024-07-13 21:45:37 +03:00

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>
);
}