LocChat/client/components/home/_home.jsx

48 lines
1.2 KiB
React
Raw Normal View History

2021-11-23 16:04:12 -05:00
import { useContext, useEffect, useState } from 'react';
2021-12-01 22:18:26 -05:00
import { useNavigate } from 'react-router';
2021-11-23 16:04:12 -05:00
import { ApiContext } from '../../utils/api_context';
import { AuthContext } from '../../utils/auth_context';
2021-12-01 22:18:26 -05:00
import { RolesContext } from '../../utils/roles_context';
import { Button } from '../common/button';
2021-11-22 16:21:53 -05:00
2021-11-20 20:18:58 -05:00
export const Home = () => {
2021-11-23 16:04:12 -05:00
const [, setAuthToken] = useContext(AuthContext);
const api = useContext(ApiContext);
2021-12-01 22:18:26 -05:00
const roles = useContext(RolesContext);
const navigate = useNavigate();
2021-11-23 16:04:12 -05:00
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(async () => {
const res = await api.get('/users/me');
setUser(res.user);
setLoading(false);
}, []);
2021-11-22 16:21:53 -05:00
const logout = async () => {
2021-11-23 16:04:12 -05:00
const res = await api.del('/sessions');
if (res.success) {
setAuthToken(null);
2021-11-22 16:21:53 -05:00
}
};
2021-11-23 16:04:12 -05:00
if (loading) {
return <div>Loading...</div>;
}
2021-11-22 16:21:53 -05:00
return (
2021-12-01 22:18:26 -05:00
<div className="p-4">
2021-12-04 23:19:54 -05:00
<h1>Welcome {user.firstName}</h1>
2021-12-01 22:18:26 -05:00
<Button type="button" onClick={logout}>
2021-11-22 16:21:53 -05:00
Logout
2021-12-01 22:18:26 -05:00
</Button>
{roles.includes('admin') && (
<Button type="button" onClick={() => navigate('/admin')}>
Admin
</Button>
)}
2021-11-22 16:21:53 -05:00
</div>
);
2021-11-20 20:18:58 -05:00
};