import React from 'react';
import { AppBar,Typography , Button , Toolbar} from '@material-ui/core';
import {Redirect, useHistory} from 'react-router-dom';
const Admin = () =>{
const history = useHistory();
let token = localStorage.getItem('token');
let loggedin = true;
if(token === null){
loggedin = false
if(loggedin === false){
return history.push('/')
}
}
const LogOut = () =>{
localStorage.removeItem('name');
localStorage.removeItem('password');
history.push('/')
}
return(
<div>
<AppBar position="static">
<Toolbar>
<Typography variant="h6">Admin Dashboard</Typography>
<Button color="secondary" variant = "contained" onClick={LogOut}>Logout</Button>
</Toolbar>
</AppBar>
</div>
)
}
export default Admin;
Asked
Active
Viewed 239 times
0

Filburt
- 17,626
- 12
- 64
- 115

Mohammad Faateh
- 143
- 11
-
if i manually write http://localhost:3000/admin i go to admin page without authorization. i dont want this. – Mohammad Faateh Jun 28 '21 at 08:25
-
I hope the following will solve it https://stackoverflow.com/questions/62172263/redirect-to-previous-page-in-reactjs – RusJaI Jun 28 '21 at 08:26
-
Please [edit] your question- don't post updates as comments. – Filburt Jun 28 '21 at 08:26
-
Does this answer your question? [How to implement authenticated routes in React Router 4?](https://stackoverflow.com/questions/43164554/how-to-implement-authenticated-routes-in-react-router-4) – thedude Jun 28 '21 at 08:31
1 Answers
0
Try this, It might help
const [token, setToken] = useState(localStorage.getItem("token"));
useEffect(() => {
if (token === null) {
return history.push("/");
}
}, [token]);
const LogOut = () => {
localStorage.removeItem("name");
localStorage.removeItem("password");
setToken(null);
};

Rahul Sharma
- 9,534
- 1
- 15
- 37