Reputation: 163
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
Reputation: 492
isAuthenticated
is true, we should redirect user to HomePage
, shouldn't we?return isAuthenticated ? <HomePage/> : <LogInPage/>;
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} />
Basically, your routers will become something like:
<Route path="/login" component={LogInPage} />
<PrivateRoute path="/home" component={HomePage} />
Upvotes: 3