forked from Roflin/gamenight
107 lines
2.5 KiB
JavaScript
107 lines
2.5 KiB
JavaScript
import './App.css';
|
|
import React, { useState, useEffect } from 'react';
|
|
import MenuBar from './components/MenuBar';
|
|
import Login from './components/Login';
|
|
import Gamenights from './components/Gamenights';
|
|
import Gamenight from './components/Gamenight';
|
|
|
|
import { get_gamenights, get_games, unpack_api_result, login } from './api/Api';
|
|
|
|
const localStorageUserKey = 'user';
|
|
|
|
function App() {
|
|
|
|
const [user, setUser] = useState(null);
|
|
const [gamenights, setGamenights] = useState([]);
|
|
const [flashData, setFlashData] = useState({});
|
|
const [games, setGames] = useState([]);
|
|
const [activeGamenightId, setActiveGamenightId] = useState(null);
|
|
|
|
const POST_HEADER = {'Content-Type': 'application/json'};
|
|
const AUTH_HEADER = {'Authorization': `Bearer ${user?.jwt}`};
|
|
|
|
const handleLogin = (input) => {
|
|
unpack_api_result(login(input), setFlashData)
|
|
.then(result => {
|
|
setUser(result.user);
|
|
localStorage.setItem(localStorageUserKey, JSON.stringify(result.user));
|
|
});
|
|
};
|
|
|
|
const onLogout = () => {
|
|
setUser(null);
|
|
localStorage.removeItem(localStorageUserKey);
|
|
};
|
|
|
|
const setFlash = (data) => {
|
|
setFlashData(data);
|
|
};
|
|
|
|
const refetchGamenights = () => {
|
|
setUser({...user});
|
|
};
|
|
|
|
const dismissActiveGamenight = () => {
|
|
setActiveGamenightId(null);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (user !== null) {
|
|
unpack_api_result(get_gamenights(user.jwt), setFlashData)
|
|
.then(result => setGamenights(result.gamenights));
|
|
}
|
|
}, [user])
|
|
|
|
useEffect(() => {
|
|
if (user !== null) {
|
|
unpack_api_result(get_games(user.jwt), setFlashData)
|
|
.then(result => setGames(result.games));
|
|
}
|
|
}, [user])
|
|
|
|
useEffect(() => {
|
|
setUser(JSON.parse(localStorage.getItem(localStorageUserKey)));
|
|
}, []);
|
|
|
|
let page;
|
|
if(user === null) {
|
|
page = (
|
|
<div className="App">
|
|
<Login onChange={handleLogin}/>
|
|
</div>
|
|
);
|
|
} else {
|
|
let mainview;
|
|
if(activeGamenightId === null) {
|
|
mainview = (
|
|
<Gamenights
|
|
user={user}
|
|
games={games}
|
|
setFlash={setFlash}
|
|
refetchGamenights={refetchGamenights}
|
|
gamenights={gamenights}
|
|
onSelectGamenight={(g) => setActiveGamenightId(g.id)}/>
|
|
)
|
|
} else {
|
|
mainview = (
|
|
<Gamenight
|
|
gamenightId={activeGamenightId}
|
|
onDismis={dismissActiveGamenight}
|
|
setFlash={setFlash}
|
|
user={user}
|
|
/>)
|
|
}
|
|
|
|
page = (
|
|
<>
|
|
<MenuBar user={user} onLogout={onLogout} />
|
|
{mainview}
|
|
</>
|
|
);
|
|
}
|
|
|
|
return page;
|
|
}
|
|
|
|
export default App;
|