Wesley Loh
Wesley Loh

Reputation: 163

How to verify a Token before I render a Home Page

I am struggling with a re-render in my project. First, I'm checking a cookie before I redirect the user to the login page. I am using Redux Store with this structure.

var initialState = {
    user: {
        auth: false,
        isFetching: false,
        isTokenFetching: false
    }
}

Fetching is for login via login form, Token fetching is for login via a Token in cookies

I'm using a customized Dynamic route to make it render based on this condition. (isFetching is when token is fetching)

const DynamicRoute = ({isFetching,isAuthenticated, ...rest}) => {
    return isFetching ? <h1>Fetching</h1> : (
        <Route {...rest} render={(props) =>{
        return isAuthenticated ?
        <HomePage/> :
        <LogInPage/>}}/>
    )
} 

This function is called before the action is dispatched, So it Renders LogInPage first, and Fetching when action is dispatched, and Render HomePage again when the token is valid.

How can I make sure it only renders the LogInPage and HomePage once. For example if token is valid (HomePage only), if token invalid (LogInPage only)

I want this dynamic route to work because I hope to use an URL for both condition.

Sorry if my explanation is bad

Upvotes: 5

Views: 1894

Answers (1)

Cam Song
Cam Song

Reputation: 492

  1. First, if isAuthenticated is true, we should redirect user to HomePage, shouldn't we?
return isAuthenticated ? <HomePage/> : <LogInPage/>;
  1. How can I make sure it only renders the LogInPage and HomePage once.

Use Redirect component to redirect user back to LogInPage like this:

return isAuthenticated ? <HomePage/> : <Redirect to="/login" />;

You can get the Redirect component from react-router-dom:

import { Redirect } from "react-router-dom";

I assume that you have defined router like this:

<Route path="/login" component={LogInPage} />
  1. IMHO, you should change the way to authenticate your workflow, because it is not good to scale for the future. Have a look at this: react-router auth-worflow example

Basically, your routers will become something like:

<Route path="/login" component={LogInPage} />
<PrivateRoute path="/home" component={HomePage} />

Upvotes: 3

Related Questions