Added logout button
This commit is contained in:
parent
75456baef5
commit
ba57c40471
14
src/App.js
14
src/App.js
|
@ -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
|
||||
|
|
|
@ -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>
|
||||
);
|
||||
|
|
Loading…
Reference in New Issue