Status Based User Redirection in Response

Right now my router looks like this:

<Router history={browserHistory}> <Route component={Provider}> <Route path="/" component={AppPage}> <Route path="login" component={LoginPage}/> <Route component={LoggedinPage}> <Route path="onboarding" component={OnboardingPage}/> <Route component={OnboardedPage}> <IndexRoute component={HomePage}/> <Route path="settings" component={SettingsPage}/> </Route> </Route> </Route> </Route> </Router> 

LoggedinPage redirected to /login if the user is not registered and OnboardedPage redirected to /onboarding if the user has not completed the onboarding stream (choosing a username, etc.). However, I think more of these conditional redirects may be needed in the future. What is the best way to handle these conditional redirects? Is it possible to have one component that handles all redirects?

+5
source share
2 answers

<Route> accept the onEnter hook, which is called when the route matches. The hook would look something like this:

 function requireAuth(nextState, replace) { if (!loggedIn()) { replace({ pathname: 'login' }); } } 

Then use it like this:

 <Route path="/" component={AppPage}> <Route path="home" component={HomePage} onEnter={requireAuth}/> <Route path="login" component={LoginPage}/> </Route> 

A more complex example that allows you to combine multiple checks:

 function checkAuth() { if (!loggedIn()) { return { pathname: 'login' }; } } function checkOnboarding() { if (!completedOnboarding()) { return { pathname: 'onboarding' }; } } function redirect(...checks) { return function(nextState, replace) { let result; checks.some(check => { result = check(); return !!result; }); result && replace(result); }; } 

Then unite!

 <Route path="/" component={AppPage}> <Route path="home" component={HomePage} onEnter={redirect(checkAuth, checkOnboarding)}/> <Route path="login" component={LoginPage}/> <Route path="onboarding" component={OnboardingPage} onEnter={redirect(checkAuth)}/> </Route> 
+1
source

You may have a function that checks if the user is registered and just import this:

 import {browserLocation} from './browser-location' export default function checkLoggedIn() { if (localStorage.jwt === null) browserLocation.pushState('/login') } 
0
source

Source: https://habr.com/ru/post/1245951/


All Articles