freewebwithme
freewebwithme

Reputation: 569

Protected page using react-router-dom doesn't work

I am trying to implement only logged in user dashboard page.

App.js

<BrowserRouter history={hist}>
  <Route path="/sign-in" exact component={SignIn} />
  <PrivateRoute path="/dashboard">
    <Dashboard />
  </PrivateRoute>
</BrowserRouter>

PrivateRoute.js

export function PrivateRoute({children, ...props}) {
  return (
    <Route {...props} render={( {location} ) =>
      isAuthenticated ? children : <Redirect to="/sign-in" />
    }
    />
  );
}

const isAuthenticated = () => {
  const userToken = JSON.parse(sessionStorage.getItem("user-token"));
  return userToken ? true : false'
}

I am checking sessionStorage for user-token, if it is null return false or true. Event though it returns "false", it redirect to Dashboard, not Sign-in page. What is my problem?

Upvotes: 0

Views: 141

Answers (2)

phen0menon
phen0menon

Reputation: 2452

The reason why router redirects to dashboard even not authenticated user is that isAuthenticated is a function. Since that, you need to call this function:

export function PrivateRoute({children, ...props}) {
  return (
    <Route {...props} render={( {location} ) =>
      isAuthenticated() ? children : <Redirect to="/sign-in" />
    }
    />
  );
}

const isAuthenticated = () => {
  const userToken = JSON.parse(sessionStorage.getItem("user-token"));
  return userToken ? true : false'
}

If you don't want to invoke function each time route changes, you can implement an immediately invoked function:

const isAuthenticated = (() => {
  const userToken = JSON.parse(sessionStorage.getItem("user-token"));
  return userToken ? true : false'
})()

export function PrivateRoute({children, ...props}) {
  return (
    <Route {...props} render={( {location} ) =>
      isAuthenticated ? children : <Redirect to="/sign-in" />
    }
    />
  );
}

Upvotes: 1

Gourav Saini
Gourav Saini

Reputation: 677

In PrivateRoute.js do this..

<Route {...props} render={( {location} ) =>
  isAuthenticated() ? children : <Redirect to="/sign-in" />
}
/>

The reason is that you are not calling the isAuthenticated. If the problem still persists, feel free to discuss.

Upvotes: 1

Related Questions