G
G
ghrtghrtq2020-04-17 11:35:08
React
ghrtghrtq, 2020-04-17 11:35:08

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>
    )
}

But the person who tested my app wrote:

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?

He is talking about the logic:
{!token && <Redirect to="/" />}
I wrote specifically in the Home.js file

And he suggested how this could be done differently:

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


This is my App.js file where I have my app's routing:

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>
   )
  }
}


And I have a question. How can I check for the presence of a token in localStorage at the routing stage (in the App.js file)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-04-17
@ghrtghrtq

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} />

https://medium.com/@s4y.solutions/react-route-4-pr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question