Answer the question
In order to leave comments, you need to log in
How can I check for the presence of a token in localStorage at the routing stage?
I am doing registration in my app. When the user has successfully passed the validation and submitted the form to the server, the token is stored in localStorage and redirected to the home page. That is, if there is no token, it is impossible to get to the home page.
I implemented it in the Home.js file like this:
const Home = () => {
const token = localStorage.getItem("myToken")
return (
<div>
{!token && <Redirect to="/" />}
<Header/>
<h1 >Home page</h1>
</div>
)
}
Not the best approach. Suppose we can have many such components - and we each have to write such logic? And if it changes, then then run around to change it everywhere?
{!token && <Redirect to="/" />}
The best option would be to check the user's token at the routing stage, that is, to divide all routes in the application into unauthorized and authorized
const history = createBrowserHistory();
class App extends React.Component {
render(){
return (
<BrowserRouter history={history}>
<div className="wrapper">
<div className="content">
<Switch>
<Route exact path="/" component={SignupForm} />
<Route path="/home" component={Home} />
<Route path="/login" component={LoginForm} />
</Switch>
</div>
</div>
</BrowserRouter>
)
}
}
Answer the question
In order to leave comments, you need to log in
googled the word protected route react
https://dev.to/skylerwebdev/setting-up-a-private-r...
the idea is to make a wrapper for routes with authorization, and do something like this
<Route exact path="/" component={SignupForm} />
<ProtectedRoute path="/home" component={Home} /> {/* если что, будет редиректить на "/" */}
<Route path="/login" component={LoginForm} />
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question