Newer
Older
import React, { FC, useContext, useEffect, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button } from '@material-ui/core';
import { InputField } from 'components/AuthUser/InputField/InputField';
import { AuthContext } from 'components/AuthUser/AuthContext';
const configDjangoCookieName = (): void => {
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN';
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.withCredentials = true;
};
const [isCookieFetched, setisCookieFetched] = useState<string>('');
configDjangoCookieName();
useEffect(() => {
const fetchCookie = async (): Promise<unknown> => {
const response = await axios('/api/web/csrf');
setisCookieFetched(response.data.token);
return null;
};
if (!isCookieFetched) fetchCookie();
}, [isCookieFetched]);
const { setRole } = useContext(AuthContext);
const { control, errors, setError, handleSubmit } = useForm<FormData>({
const onSubmit: SubmitHandler<FormData> = (values: FormData) => {
csrfmiddlewaretoken: isCookieFetched,
{
headers: {
'Content-Type': 'application/json',
},
},
)
.then((response) => {
if (response.data.status === 'fail') {
message: 'Something went wrong with username',
});
setError('password', {
type: 'server',
message: 'Something went wrong with password',
});
} else if (response.data.status === 'success') {
history.replace(AuthRoutes.dashboard);
}
<>
<form
className={classes.form}
onSubmit={handleSubmit(onSubmit)}
data-testid="Form"
label="username"
error={!!errors.username}
errorMessage="Insert username"
control={control}
rules={{
minLength: 8,
maxLength: 60,
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</>