]> git.localhorst.tv Git - alttp.git/blob - resources/js/components/App.js
b5bd9c9fdfd8388d500d97f5ae8e10b9e594719b
[alttp.git] / resources / js / components / App.js
1 import axios from 'axios';
2 import React, { useEffect, useState } from 'react';
3 import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
4
5 import Header from './common/Header';
6 import Front from './pages/Front';
7 import Tournament from './pages/Tournament';
8 import UserContext from '../helpers/UserContext';
9
10 const App = () => {
11         const [user, setUser] = useState(null);
12
13         const checkAuth = async () => {
14                 try {
15                         const response = await axios.get('/api/user');
16                         setUser(response.data);
17                 } catch (e) {
18                         setUser(null);
19                 }
20         };
21
22         const doLogout = async () => {
23                 await axios.post('/logout');
24                 await checkAuth();
25         };
26
27         useEffect(() => {
28                 let timer = null;
29                 axios
30                         .get('/sanctum/csrf-cookie')
31                         .then(() => {
32                                 checkAuth();
33                                 timer = setInterval(checkAuth, 15 * 60 * 1000);
34                         });
35                 return () => {
36                         if (timer) clearInterval(timer);
37                 };
38         }, []);
39
40         return <BrowserRouter>
41                 <UserContext.Provider value={user}>
42                         <Header doLogout={doLogout} />
43                         {user ?
44                                 <Routes>
45                                         <Route path="tournaments/:id" element={<Tournament />} />
46                                         <Route path="*" element={<Navigate to="/tournaments/1" />} />
47                                 </Routes>
48                         : <Front />}
49                 </UserContext.Provider>
50         </BrowserRouter>;
51 };
52
53 export default App;