Added logout button

This commit is contained in:
Steve White 2024-10-12 11:27:42 -05:00
parent 75456baef5
commit ba57c40471
2 changed files with 30 additions and 5 deletions

View File

@ -6,10 +6,14 @@ import Login from './components/Login';
import Boxes from './components/Boxes';
import Items from './components/Items';
import Navbar from './components/Navbar'; // Correct import here
import { createContext } from 'react';
import './styles.css'
export const AppContext = createContext();
function App() {
const [token, setToken] = useState(localStorage.getItem('token'));
useEffect(() => {
if (token) {
localStorage.setItem('token', token);
@ -17,9 +21,12 @@ function App() {
}, [token]);
return (
<Router>
<AppRoutes token={token} setToken={setToken} />
</Router>
<AppContext.Provider value={{ token, setToken }}>
<Router>
<Navbar />
<AppRoutes token={token} setToken={setToken} />
</Router>
</AppContext.Provider>
);
}
@ -28,7 +35,6 @@ function AppRoutes({ token, setToken }) {
return (
<>
<Navbar />
<Routes>
<Route path="/login" element={<Login setToken={setToken} />} />
<Route

View File

@ -1,9 +1,27 @@
// src/components/Navbar.js
import React from 'react';
import { AppBar, Toolbar, Typography, Button } from '@mui/material';
import { Link } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import { useContext } from 'react';
import { AppContext } from '../App';
export default function Navbar() {
const navigate = useNavigate();
const context = useContext(AppContext);
console.log('Context:', context);
if (!context) {
throw new Error('AppContext is not available');
}
const { setToken } = context;
const handleLogout = () => {
localStorage.removeItem('token');
setToken(null);
navigate('/login');
};
return (
<AppBar position="static">
<Toolbar>
@ -13,6 +31,7 @@ export default function Navbar() {
<Button color="inherit" component={Link} to="/login">Login</Button>
<Button color="inherit" component={Link} to="/boxes">Boxes</Button>
<Button color="inherit" component={Link} to="/items">Items</Button>
<Button color="inherit" onClick={handleLogout}>Logout</Button>
</Toolbar>
</AppBar>
);