LocChat/client/app.jsx

52 lines
1.5 KiB
React
Raw Permalink Normal View History

2021-11-23 16:04:12 -05:00
import { useState, useEffect } from 'react';
2021-11-20 21:34:10 -05:00
import { HashRouter } from 'react-router-dom';
2021-11-20 20:18:58 -05:00
import { Router } from './components/router';
2021-11-23 16:04:12 -05:00
import { ApiContext } from './utils/api_context';
import { AuthContext } from './utils/auth_context';
import { useApi } from './utils/use_api';
import { useJwtRefresh } from './utils/use_jwt_refresh';
2021-12-01 22:18:26 -05:00
import { RolesContext } from './utils/roles_context';
import { parseJwt } from './utils/parse_jwt';
import { Toaster } from 'react-hot-toast';
2021-12-27 12:39:59 -05:00
import './app.css';
import 'leaflet/dist/leaflet.css';
2021-11-20 21:34:10 -05:00
2021-11-23 16:04:12 -05:00
export const App = () => {
const [authToken, setAuthToken] = useState(null);
const [loading, setLoading] = useState(true);
// Refresh the jwt token automatically
useJwtRefresh(authToken, setAuthToken);
// api instance
const api = useApi(authToken);
// get initial jwt using refresh token
useEffect(async () => {
const result = await api.get('/refresh_token');
if (result.token) {
setAuthToken(result.token);
2021-11-20 21:34:10 -05:00
}
2021-11-23 16:04:12 -05:00
setLoading(false);
}, []);
2021-11-16 21:14:46 -05:00
2021-12-01 22:18:26 -05:00
const jwtPayload = parseJwt(authToken);
// don't display anything while trying to get user token
2021-11-30 17:40:07 -05:00
// can display a loading screen here if desired
2021-11-23 16:04:12 -05:00
if (loading) return null;
2021-11-20 21:34:10 -05:00
2021-11-16 21:14:46 -05:00
return (
2021-11-23 16:04:12 -05:00
<AuthContext.Provider value={[authToken, setAuthToken]}>
<ApiContext.Provider value={api}>
2021-12-01 22:18:26 -05:00
<RolesContext.Provider value={jwtPayload.roles}>
<Toaster position="top-center" />
2021-12-01 22:18:26 -05:00
<HashRouter>
<Router />
</HashRouter>
</RolesContext.Provider>
2021-11-23 16:04:12 -05:00
</ApiContext.Provider>
</AuthContext.Provider>
2021-11-16 21:14:46 -05:00
);
};