Add currentUser and isAuthenticated to authcontext

This commit is contained in:
2020-08-22 18:33:42 +02:00
parent a52bc8f7ab
commit 3356c380d7
7 changed files with 72 additions and 15 deletions

View File

@@ -5,14 +5,16 @@ import { useAuth } from '../helpers/authContext';
import { NavBar } from '../components';
export default function Dashboard() {
const { authToken } = useAuth();
const { authToken, isAuthenticated, currentUser } = useAuth();
return (
<>
<NavBar title='Meeting Planner' />
<Panel header={<h3>Dashboard</h3>} bordered >
<Panel header={<h3>Dashboard</h3>} bordered>
<p>This is just experimenting with stuff.</p>
<p>{authToken}</p>
<p>Authenticated: {isAuthenticated.toString()}</p>
<p>Current user: {currentUser.username}</p>
</Panel>
</>
);

View File

@@ -5,7 +5,7 @@ import { useAuth } from '../helpers/authContext';
import { NavBar } from '../components';
export default function Home() {
const { authToken } = useAuth();
const { authToken, isAuthenticated } = useAuth();
return (
<>
@@ -13,6 +13,7 @@ export default function Home() {
<Panel header={<h3>Home</h3>} bordered>
<p>This will be the home page</p>
<p>{authToken}</p>
<p>Authenticated: {isAuthenticated.toString()}</p>
</Panel>
</>
);

View File

@@ -22,7 +22,12 @@ export default function Login() {
password: '',
});
const { setAuthToken, authToken } = useAuth();
const {
setAuthToken,
setIsAuthenticated,
setCurrentUser,
isAuthenticated,
} = useAuth();
const handleChange = (value, evt) => {
setCredentials({
@@ -36,6 +41,8 @@ export default function Login() {
.post('/auth/login', credentials)
.then((response) => {
setAuthToken(response.data.token);
setCurrentUser(response.data.user);
setIsAuthenticated(true);
})
.catch((error) => {
if (error.response.status === 401) {
@@ -45,7 +52,7 @@ export default function Login() {
});
};
if (authToken) {
if (isAuthenticated) {
return <Redirect to='/dashboard' />;
}

View File

@@ -26,7 +26,12 @@ export default function Register() {
timezone: '',
});
const { setAuthToken, authToken } = useAuth();
const {
setAuthToken,
setIsAuthenticated,
setCurrentUser,
isAuthenticated,
} = useAuth();
const handleChange = (value, evt) => {
setNewUser({
@@ -54,13 +59,15 @@ export default function Register() {
.post('/auth/register', newUser)
.then((response) => {
setAuthToken(response.data.token);
setCurrentUser(response.data.user);
setIsAuthenticated(true);
})
.catch((error) => {
setError('Failed to add new account.');
});
};
if (authToken) {
if (isAuthenticated) {
return <Redirect to='/dashboard' />;
}