Implement login request

This commit is contained in:
2020-08-19 13:38:25 +02:00
parent e1641b32d1
commit 125a03f529
6 changed files with 39 additions and 51 deletions

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import axios from 'axios';
import { backend } from '../utils/http-common';
import {
Panel,
Form,
@@ -8,55 +8,38 @@ import {
FormControl,
ControlLabel,
Button,
Message,
} 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 history = useHistory();
const [error, setError] = useState(false);
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)
backend
.post('/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('');
setUserSession(response.data.token, response.data.user);
history.push('/dashboard');
})
.catch((error) => {
console.log('ERROR', error);
setLoading(false);
if (error.response.status === 401)
setError(error.response.data.message);
setError('Incorrect credentials. Please try again.');
else setError('Something went wrong. Please try again later.');
});
};
@@ -65,6 +48,7 @@ export default function Login({ title }) {
<>
<NavBar title={title} />
<Panel bordered style={boxStyle}>
{error && <Message type='error' description={error} />}
<Form>
<FormGroup>
<ControlLabel>Email</ControlLabel>