frontend/src/screens/Login.js

114 lines
2.4 KiB
JavaScript

import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import axios from 'axios';
import {
Panel,
Form,
FormGroup,
FormControl,
ControlLabel,
Button,
} from 'rsuite';
import { setUserSession } from '../utils/common';
import NavBar from './../components/Navbar/NavBar';
export default function Login({ title }) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [credentials, setCredentials] = useState({
email: '',
password: '',
});
const history = useHistory();
// handle input fields
const handleChange = (value, evt) => {
console.log(value, evt.target.name);
setCredentials({
...credentials,
[evt.target.name]: value,
});
};
// handle button click of login form
const handleLogin = () => {
setError(null);
setLoading(true);
console.log(credentials.email, credentials.password);
axios
.post('http://localhost:3000/api/auth/login', credentials)
.then((response) => {
setLoading(false);
console.log('RESPONSE', response);
localStorage.setItem(
'data',
JSON.stringify({
token: response.data.token,
user: response.data.user,
}),
);
// TODO: Working redirection
history.push('');
})
.catch((error) => {
console.log('ERROR', error);
setLoading(false);
if (error.response.status === 401)
setError(error.response.data.message);
else setError('Something went wrong. Please try again later.');
});
};
return (
<>
<NavBar title={title} />
<Panel bordered style={boxStyle}>
<Form>
<FormGroup>
<ControlLabel>Email</ControlLabel>
<FormControl
name='email'
type='email'
formValue={credentials.email}
onChange={handleChange}
/>
</FormGroup>
<ControlLabel>Password</ControlLabel>
<FormGroup>
<FormControl
name='password'
type='password'
formValue={credentials.password}
onChange={handleChange}
/>
</FormGroup>
<FormGroup>
<Button
appearance='primary'
block
size='lg'
onClick={handleLogin}
>
Sign in
</Button>
</FormGroup>
<Button appearance='link'>Forgot password?</Button>
</Form>
</Panel>
</>
);
}
// TODO Move to a .less file
const boxStyle = {
maxWidth: 373,
margin: '0 auto',
borderRadius: 7,
background: 'white',
marginTop: '10vh',
marginBottom: '10vh',
padding: '1rem',
};