Refactor authentication with Context
This commit is contained in:
19
src/screens/Home.js
Normal file
19
src/screens/Home.js
Normal file
@@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import { Panel } from 'rsuite';
|
||||
|
||||
import NavBar from '../components/Navbar/NavBar';
|
||||
|
||||
const boxStyle = {
|
||||
margin: '50px 10px',
|
||||
};
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<>
|
||||
<NavBar title='Meeting Planner' />
|
||||
<Panel header={<h3>Home</h3>} bordered style={boxStyle}>
|
||||
<p>This will be the home page</p>
|
||||
</Panel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
import { backend } from '../utils/http-common';
|
||||
import { Redirect } from 'react-router-dom';
|
||||
import {
|
||||
Panel,
|
||||
Form,
|
||||
@@ -11,18 +10,19 @@ import {
|
||||
Message,
|
||||
} from 'rsuite';
|
||||
|
||||
import { setUserSession } from '../utils/common';
|
||||
import NavBar from './../components/Navbar/NavBar';
|
||||
import { backend } from '../helpers/http-common';
|
||||
import { useAuth } from '../helpers/authContext';
|
||||
|
||||
export default function Login() {
|
||||
const history = useHistory();
|
||||
|
||||
const [error, setError] = useState(false);
|
||||
const [credentials, setCredentials] = useState({
|
||||
email: '',
|
||||
password: '',
|
||||
});
|
||||
|
||||
const { setAuthToken, authToken } = useAuth();
|
||||
|
||||
const handleChange = (value, evt) => {
|
||||
setCredentials({
|
||||
...credentials,
|
||||
@@ -34,16 +34,20 @@ export default function Login() {
|
||||
backend
|
||||
.post('/auth/login', credentials)
|
||||
.then((response) => {
|
||||
setUserSession(response.data.token, response.data.user);
|
||||
history.push('/dashboard');
|
||||
setAuthToken(response.data.token);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.response.status === 401)
|
||||
setError('Incorrect credentials. Please try again.');
|
||||
else setError('Something went wrong. Please try again later.');
|
||||
if (error.response.status === 401) {
|
||||
setError('The credentials provided were incorrect.');
|
||||
} else
|
||||
setError('Something went wrong. Please try again later.');
|
||||
});
|
||||
};
|
||||
|
||||
if (authToken) {
|
||||
return <Redirect to='/dashboard' />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavBar title='Login' />
|
||||
|
||||
Reference in New Issue
Block a user