send user to /login if they don't have a token

This commit is contained in:
Steve White 2024-10-12 11:08:19 -05:00
parent ab5ccac8e3
commit 75456baef5
1 changed files with 28 additions and 8 deletions

View File

@ -1,6 +1,6 @@
// src/App.js
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import Login from './components/Login';
import Boxes from './components/Boxes';
@ -15,17 +15,37 @@ function App() {
localStorage.setItem('token', token);
}
}, [token]);
return (
<Router>
<Navbar />
<Routes>
<Route path="/login" element={<Login setToken={setToken} />} />
<Route path="/boxes" element={<Boxes token={token} />} />
<Route path="/items" element={<Items token={token} />} />
<Route path="/boxes/:id/items" element={<Items box_id={useParams().id} token={token} />} />
</Routes>
<AppRoutes token={token} setToken={setToken} />
</Router>
);
}
function AppRoutes({ token, setToken }) {
const { id } = useParams(); // Move useParams here
return (
<>
<Navbar />
<Routes>
<Route path="/login" element={<Login setToken={setToken} />} />
<Route
path="/boxes"
element={token ? <Boxes token={token} /> : <Navigate to="/login" replace />}
/>
<Route
path="/items"
element={token ? <Items token={token} /> : <Navigate to="/login" replace />}
/>
<Route
path="/boxes/:id/items"
element={token ? <Items box_id={id} token={token} /> : <Navigate to="/login" replace />}
/>
<Route path="*" element={<Navigate to={token ? "/boxes" : "/login"} replace />} />
</Routes>
</>
);
}
export default App;