gamenight/frontend/src/App.js

141 lines
3.3 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';
const localStorageUserKey = 'user';
function App() {
const [user, setUser] = useState(null);
const [gamenights, setGamenights] = useState([]);
const [flashData, setFlashData] = useState({});
const [games, setGames] = useState([]);
const [activeGamenight, setActiveGamenight] = useState(null);
const handleLogin = (input) => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input)
};
fetch('api/login', requestOptions)
.then(response => response.json())
.then(data => {
if(data.result === "Ok") {
setUser(data.user);
localStorage.setItem(localStorageUserKey, JSON.stringify(data.user));
} else {
setFlashData({
type: "Error",
message: data.message
});
}
});
};
const onLogout = () => {
setUser(null);
localStorage.removeItem(localStorageUserKey);
};
const setFlash = (data) => {
setFlashData(data);
};
const refetchGamenights = () => {
setUser({...user});
};
const dismissActiveGamenight = () => {
setActiveGamenight(null);
};
useEffect(() => {
if (user !== null) {
const requestOptions = {
method: 'GET',
headers: { 'Authorization': `Bearer ${user.jwt}` },
};
fetch('api/gamenights', requestOptions)
.then(response => response.json())
.then(data => {
if(data.result === "Ok") {
setGamenights(data.gamenights)
} else {
setFlashData({
type: "Error",
message: data.message
});
}
});
}
}, [user])
useEffect(() => {
if (user !== null) {
const requestOptions = {
method: 'GET',
headers: { 'Authorization': `Bearer ${user.jwt}` },
};
fetch('api/games', requestOptions)
.then(response => response.json())
.then(data => {
if(data.result === "Ok") {
setGames(data.games)
} else {
setFlashData({
type: "Error",
message: data.message
});
}
});
}
}, [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(activeGamenight === null) {
mainview = (
<Gamenights
user={user}
games={games}
setFlash={setFlash}
refetchGamenights={refetchGamenights}
gamenights={gamenights}
onSelectGamenight={(g) => setActiveGamenight(g)}/>
)
} else {
mainview = (
<Gamenight
gamenight={activeGamenight}
onDismis={dismissActiveGamenight}
/>)
}
page = (
<>
<MenuBar user={user} onLogout={onLogout} />
{mainview}
</>
);
}
return page;
}
export default App;