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';
|
2022-03-30 17:18:16 -04:00
|
|
|
import { Map } from '../map/_map';
|
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
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-03-31 00:15:20 -04:00
|
|
|
const joinRoom = async (id, userPosition) => {
|
|
|
|
const res = await api.get(`/chat_rooms/${id}/joinable?lat=${userPosition.lat}&lng=${userPosition.lng}`);
|
|
|
|
if (res) {
|
|
|
|
navigate(`/rooms/${id}`);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-11-23 16:04:12 -05:00
|
|
|
if (loading) {
|
|
|
|
return <div>Loading...</div>;
|
|
|
|
}
|
|
|
|
|
2021-11-22 16:21:53 -05:00
|
|
|
return (
|
2022-03-30 17:18:16 -04:00
|
|
|
<>
|
|
|
|
<div className="p-4">
|
|
|
|
<h1>Welcome {user.firstName}</h1>
|
|
|
|
<Button type="button" onClick={logout}>
|
|
|
|
Logout
|
2021-12-01 22:18:26 -05:00
|
|
|
</Button>
|
2022-03-30 17:18:16 -04:00
|
|
|
{roles.includes('admin') && (
|
|
|
|
<Button type="button" onClick={() => navigate('/admin')}>
|
|
|
|
Admin
|
|
|
|
</Button>
|
|
|
|
)}
|
|
|
|
</div>
|
2022-03-31 00:15:20 -04:00
|
|
|
<Map user={user} joinRoom={joinRoom} />
|
2022-03-30 17:18:16 -04:00
|
|
|
</>
|
2021-11-22 16:21:53 -05:00
|
|
|
);
|
2021-11-20 20:18:58 -05:00
|
|
|
};
|