nquest/frontend/src/App.jsx

74 lines
2.1 KiB
React
Raw Normal View History

2023-11-01 23:21:12 +03:00
import { Navigate, Route, RouterProvider, createBrowserRouter, createRoutesFromElements, useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import Layout from './components/Layout'
import Index from './pages/Index'
import Login from './pages/Login'
import Register from './pages/Register'
import NoMatch from './pages/NoMatch'
import { UserProvider } from './store/user'
import { ajax } from './utils/fetch'
import Engine from './pages/Engine'
2024-01-20 21:37:49 +03:00
import Quests from './pages/Quests'
2023-11-19 22:54:54 +03:00
2023-11-01 23:21:12 +03:00
const router = createBrowserRouter(
createRoutesFromElements(
<Route
path="/"
id="root"
element={<Layout />}
2024-01-20 21:37:49 +03:00
loader={async () => ajax("/api/user").catch(x => {console.log(x); return null})}
2023-11-01 23:21:12 +03:00
>
2023-11-19 22:54:54 +03:00
<Route
index
element={<Index />}
2024-01-20 21:37:49 +03:00
/>
<Route
id="quests"
path="/quests"
element={<Auth><Quests /></Auth>}
2024-01-20 23:59:09 +03:00
loader={() => ajax("/api/games").catch(x => {console.log(x); return null})}
/>
2023-11-01 23:21:12 +03:00
<Route path="login" element={<Login />} />
<Route path="register" element={<Register />} />
<Route
path="go/:gameId"
element={<Auth><Engine /></Auth>}
2024-01-20 23:59:09 +03:00
loader={({ params }) => ajax(`/api/engine/${params.gameId}`).catch(x => {console.log(x); return null})}
2023-11-01 23:21:12 +03:00
/>
{/* <Route
2023-11-19 22:54:54 +03:00
path="admin"
element={<Auth role="creator"><Admin /></Auth>}
loader={() => ajax(`/api/admin/games`)}
/>
<Route
path="admin/games/new"
element={<Auth role="creator"><AdminGame /></Auth>}
loader={() => ({
title: "Новая игра",
tasks: []
})}
/> */}
2023-11-01 23:21:12 +03:00
<Route path="*" element={<NoMatch />} />
</Route>
)
);
function App() {
return (
<RouterProvider router={router} />
)
}
function Auth({ children }) {
const baseUser = useRouteLoaderData("root")
2023-11-19 22:54:54 +03:00
const { user } = UserProvider.useContainer();
2023-11-01 23:21:12 +03:00
const location = useLocation();
if (!user && !baseUser) {
2023-11-19 22:54:54 +03:00
return <Navigate to="/login" state={{ from: location }} replace />;
2023-11-01 23:21:12 +03:00
}
2023-11-19 22:54:54 +03:00
2023-11-01 23:21:12 +03:00
return children;
}
export default App