react-router-dom with react hooks Does not redirect to correct route2019 Community Moderator ElectionProgrammatically navigate using react routerReact Router with optional path parameterNested routes with react router v4Programmatically navigate using react router V4How to push to History in React Router v4?Authentication with Passport + Facebook + Express + create-react-app + React-Router + proxyReact Routing not renderingHow to use Apollo Client + React Router to implement private routes and redirection based on user status?React routing and private routesRedirect router on after login
Short story about an infectious indestructible metal bar?
Are Wave equations equivalent to Maxwell equations in free space?
Create chunks from an array
Are there other characters in the Star Wars universe who had damaged bodies and needed to wear an outfit like Darth Vader?
I've given my players a lot of magic items. Is it reasonable for me to give them harder encounters?
Why won't the strings command stop?
Why is there an extra space when I type "ls" on the Desktop?
I can't die. Who am I?
School performs periodic password audits. Is my password compromised?
How can I be pwned if I'm not registered on the compromised site?
Ultrafilters as a double dual
Iron deposits mined from under the city
An Undercover Army
Sundering Titan and basic normal lands and snow lands
Professor forcing me to attend a conference
Was it really inappropriate to write a pull request for the company I interviewed with?
Too soon for a plot twist?
Can inspiration allow the Rogue to make a Sneak Attack?
A bug in Excel? Conditional formatting for marking duplicates also highlights unique value
How to make sure I'm assertive enough in contact with subordinates?
Is divide-by-zero a security vulnerability?
Can a space-faring robot still function over a billion years?
Do natural melee weapons (from racial traits) trigger Improved Divine Smite?
How do we objectively assess if a dialogue sounds unnatural or cringy?
react-router-dom with react hooks Does not redirect to correct route
2019 Community Moderator ElectionProgrammatically navigate using react routerReact Router with optional path parameterNested routes with react router v4Programmatically navigate using react router V4How to push to History in React Router v4?Authentication with Passport + Facebook + Express + create-react-app + React-Router + proxyReact Routing not renderingHow to use Apollo Client + React Router to implement private routes and redirection based on user status?React routing and private routesRedirect router on after login
I am new to react and I am sure there is an explanation I do not understand, but I cannot find an answer...
I Want to app if user is logged in,so I followed some guide and created HOC(PrivateRoute) but for some reason I keep ending up in the login page of the app,
Even if localStorage contains a valid JWT and I am asking for the specific path(/wallet/portfolio), it is still redirecting me to login page,
can someone please help me understand the issue(I am using typescript but I am sure it is unrelated to the issue)
My Main Component(App.tsx)
//imports...
export const App = () =>
const[jWTContext, setJWTContext] = useState(jWTContextInitialState);
const[isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() =>
if (!isLoggedIn)
jWTContext.isValid().then(loggedIn =>
setIsLoggedIn(loggedIn);
).catch(() => setIsLoggedIn(false));
);
return (
<JWTContext.Provider value=jWTContext>
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
</JWTContext.Provider>
);
;
PrivateRoute.tsx(copied from a guide on the web...)
import * as React from 'react';
import Route, Redirect, RouteProps from 'react-router-dom';
interface PrivateRouteProps extends RouteProps
component: any;
isSignedIn: boolean;
const PrivateRoute = (props: PrivateRouteProps) =>
const component: Component, isSignedIn, ...rest = props;
return (
<Route
...rest
render=(routeProps) =>
isSignedIn ? (
<Component ...routeProps />
) : (
<Redirect
to=
pathname: '/wallet/login',
state: from: routeProps.location
/>
)
/>
);
;
export default PrivateRoute;
JWTContext.tsx(My Context provider):
import React from 'react';
import JWTBody, JWTHeader, JWTToken from "../interfaces/JWTToken"
export interface JWTContext null): void;
isValid(): Promise<boolean>;
updateFromLocalStorage(): (JWTToken
export const jWTContextInitialState : JWTContext =
jWTToken: initFromLocalStorage(),
setJWTToken: (jWTToken) =>
jWTContextInitialState.jWTToken = jWTToken;
,
isValid: async() =>
if (jWTContextInitialState.jWTToken)
let response = await fetch("/auth/tokenvalid",
method: "GET",
headers:
"Content-Type": "application/json",
"Authorization": JSON.stringify(jWTContextInitialState.jWTToken));
let res = await response.json();
if (res.code === 200)
return true;
return false;
,
updateFromLocalStorage: () =>
return initFromLocalStorage()
;
function initFromLocalStorage()
let localStorageToken = localStorage.getItem("velonaJWT");
if (localStorageToken)
return parseJwt(localStorageToken);
return null;
function parseJwt (token: string): JWTToken
token = token.replace("Bearer ", "");
let tokenArray = token.split('.');
let header = tokenArray[0];
header = header.replace('-', '+').replace('_', '/');
let bufferHeader = Buffer.from(header, "base64");
let dataHeader: JWTHeader = JSON.parse(bufferHeader.toString());
let body = tokenArray[1];
body = body.replace('-', '+').replace('_', '/');
let bufferBody = Buffer.from(body, "base64");
let dataBody: JWTBody = JSON.parse(bufferBody.toString());
return (
header: dataHeader,
body: dataBody,
sig: tokenArray[2]
);
//return JWTToken(JSON.parse(bufferHeader.toString()), JSON.parse(bufferBody.toString()), tokenArray[2])
export const JWTContext = React.createContext(jWTContextInitialState);
and finally the (JWTToken.tsx -> just for interfaces)
// represent velona WJT token
export interface JWTToken
header: JWTHeader,
body: JWTBody,
sig: string,
export interface JWTHeader
typ: string,
alg: string
export interface JWTBody
sub: number,
jti: string,
authorities: Authorities[],
iat: number,
nbf: number,
exp: number,
environment: string
export enum Authorities
ROLE_USER,
ROLE_TRUSTEE,
ROLE_EMPLOYEE,
ROLE_ADMIN
reactjs typescript react-router-v4 react-hooks
add a comment |
I am new to react and I am sure there is an explanation I do not understand, but I cannot find an answer...
I Want to app if user is logged in,so I followed some guide and created HOC(PrivateRoute) but for some reason I keep ending up in the login page of the app,
Even if localStorage contains a valid JWT and I am asking for the specific path(/wallet/portfolio), it is still redirecting me to login page,
can someone please help me understand the issue(I am using typescript but I am sure it is unrelated to the issue)
My Main Component(App.tsx)
//imports...
export const App = () =>
const[jWTContext, setJWTContext] = useState(jWTContextInitialState);
const[isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() =>
if (!isLoggedIn)
jWTContext.isValid().then(loggedIn =>
setIsLoggedIn(loggedIn);
).catch(() => setIsLoggedIn(false));
);
return (
<JWTContext.Provider value=jWTContext>
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
</JWTContext.Provider>
);
;
PrivateRoute.tsx(copied from a guide on the web...)
import * as React from 'react';
import Route, Redirect, RouteProps from 'react-router-dom';
interface PrivateRouteProps extends RouteProps
component: any;
isSignedIn: boolean;
const PrivateRoute = (props: PrivateRouteProps) =>
const component: Component, isSignedIn, ...rest = props;
return (
<Route
...rest
render=(routeProps) =>
isSignedIn ? (
<Component ...routeProps />
) : (
<Redirect
to=
pathname: '/wallet/login',
state: from: routeProps.location
/>
)
/>
);
;
export default PrivateRoute;
JWTContext.tsx(My Context provider):
import React from 'react';
import JWTBody, JWTHeader, JWTToken from "../interfaces/JWTToken"
export interface JWTContext null): void;
isValid(): Promise<boolean>;
updateFromLocalStorage(): (JWTToken
export const jWTContextInitialState : JWTContext =
jWTToken: initFromLocalStorage(),
setJWTToken: (jWTToken) =>
jWTContextInitialState.jWTToken = jWTToken;
,
isValid: async() =>
if (jWTContextInitialState.jWTToken)
let response = await fetch("/auth/tokenvalid",
method: "GET",
headers:
"Content-Type": "application/json",
"Authorization": JSON.stringify(jWTContextInitialState.jWTToken));
let res = await response.json();
if (res.code === 200)
return true;
return false;
,
updateFromLocalStorage: () =>
return initFromLocalStorage()
;
function initFromLocalStorage()
let localStorageToken = localStorage.getItem("velonaJWT");
if (localStorageToken)
return parseJwt(localStorageToken);
return null;
function parseJwt (token: string): JWTToken
token = token.replace("Bearer ", "");
let tokenArray = token.split('.');
let header = tokenArray[0];
header = header.replace('-', '+').replace('_', '/');
let bufferHeader = Buffer.from(header, "base64");
let dataHeader: JWTHeader = JSON.parse(bufferHeader.toString());
let body = tokenArray[1];
body = body.replace('-', '+').replace('_', '/');
let bufferBody = Buffer.from(body, "base64");
let dataBody: JWTBody = JSON.parse(bufferBody.toString());
return (
header: dataHeader,
body: dataBody,
sig: tokenArray[2]
);
//return JWTToken(JSON.parse(bufferHeader.toString()), JSON.parse(bufferBody.toString()), tokenArray[2])
export const JWTContext = React.createContext(jWTContextInitialState);
and finally the (JWTToken.tsx -> just for interfaces)
// represent velona WJT token
export interface JWTToken
header: JWTHeader,
body: JWTBody,
sig: string,
export interface JWTHeader
typ: string,
alg: string
export interface JWTBody
sub: number,
jti: string,
authorities: Authorities[],
iat: number,
nbf: number,
exp: number,
environment: string
export enum Authorities
ROLE_USER,
ROLE_TRUSTEE,
ROLE_EMPLOYEE,
ROLE_ADMIN
reactjs typescript react-router-v4 react-hooks
Does it work if you as an experiment change the logged in state touseState(true)
?
– Tholle
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
1
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday
add a comment |
I am new to react and I am sure there is an explanation I do not understand, but I cannot find an answer...
I Want to app if user is logged in,so I followed some guide and created HOC(PrivateRoute) but for some reason I keep ending up in the login page of the app,
Even if localStorage contains a valid JWT and I am asking for the specific path(/wallet/portfolio), it is still redirecting me to login page,
can someone please help me understand the issue(I am using typescript but I am sure it is unrelated to the issue)
My Main Component(App.tsx)
//imports...
export const App = () =>
const[jWTContext, setJWTContext] = useState(jWTContextInitialState);
const[isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() =>
if (!isLoggedIn)
jWTContext.isValid().then(loggedIn =>
setIsLoggedIn(loggedIn);
).catch(() => setIsLoggedIn(false));
);
return (
<JWTContext.Provider value=jWTContext>
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
</JWTContext.Provider>
);
;
PrivateRoute.tsx(copied from a guide on the web...)
import * as React from 'react';
import Route, Redirect, RouteProps from 'react-router-dom';
interface PrivateRouteProps extends RouteProps
component: any;
isSignedIn: boolean;
const PrivateRoute = (props: PrivateRouteProps) =>
const component: Component, isSignedIn, ...rest = props;
return (
<Route
...rest
render=(routeProps) =>
isSignedIn ? (
<Component ...routeProps />
) : (
<Redirect
to=
pathname: '/wallet/login',
state: from: routeProps.location
/>
)
/>
);
;
export default PrivateRoute;
JWTContext.tsx(My Context provider):
import React from 'react';
import JWTBody, JWTHeader, JWTToken from "../interfaces/JWTToken"
export interface JWTContext null): void;
isValid(): Promise<boolean>;
updateFromLocalStorage(): (JWTToken
export const jWTContextInitialState : JWTContext =
jWTToken: initFromLocalStorage(),
setJWTToken: (jWTToken) =>
jWTContextInitialState.jWTToken = jWTToken;
,
isValid: async() =>
if (jWTContextInitialState.jWTToken)
let response = await fetch("/auth/tokenvalid",
method: "GET",
headers:
"Content-Type": "application/json",
"Authorization": JSON.stringify(jWTContextInitialState.jWTToken));
let res = await response.json();
if (res.code === 200)
return true;
return false;
,
updateFromLocalStorage: () =>
return initFromLocalStorage()
;
function initFromLocalStorage()
let localStorageToken = localStorage.getItem("velonaJWT");
if (localStorageToken)
return parseJwt(localStorageToken);
return null;
function parseJwt (token: string): JWTToken
token = token.replace("Bearer ", "");
let tokenArray = token.split('.');
let header = tokenArray[0];
header = header.replace('-', '+').replace('_', '/');
let bufferHeader = Buffer.from(header, "base64");
let dataHeader: JWTHeader = JSON.parse(bufferHeader.toString());
let body = tokenArray[1];
body = body.replace('-', '+').replace('_', '/');
let bufferBody = Buffer.from(body, "base64");
let dataBody: JWTBody = JSON.parse(bufferBody.toString());
return (
header: dataHeader,
body: dataBody,
sig: tokenArray[2]
);
//return JWTToken(JSON.parse(bufferHeader.toString()), JSON.parse(bufferBody.toString()), tokenArray[2])
export const JWTContext = React.createContext(jWTContextInitialState);
and finally the (JWTToken.tsx -> just for interfaces)
// represent velona WJT token
export interface JWTToken
header: JWTHeader,
body: JWTBody,
sig: string,
export interface JWTHeader
typ: string,
alg: string
export interface JWTBody
sub: number,
jti: string,
authorities: Authorities[],
iat: number,
nbf: number,
exp: number,
environment: string
export enum Authorities
ROLE_USER,
ROLE_TRUSTEE,
ROLE_EMPLOYEE,
ROLE_ADMIN
reactjs typescript react-router-v4 react-hooks
I am new to react and I am sure there is an explanation I do not understand, but I cannot find an answer...
I Want to app if user is logged in,so I followed some guide and created HOC(PrivateRoute) but for some reason I keep ending up in the login page of the app,
Even if localStorage contains a valid JWT and I am asking for the specific path(/wallet/portfolio), it is still redirecting me to login page,
can someone please help me understand the issue(I am using typescript but I am sure it is unrelated to the issue)
My Main Component(App.tsx)
//imports...
export const App = () =>
const[jWTContext, setJWTContext] = useState(jWTContextInitialState);
const[isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() =>
if (!isLoggedIn)
jWTContext.isValid().then(loggedIn =>
setIsLoggedIn(loggedIn);
).catch(() => setIsLoggedIn(false));
);
return (
<JWTContext.Provider value=jWTContext>
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
</JWTContext.Provider>
);
;
PrivateRoute.tsx(copied from a guide on the web...)
import * as React from 'react';
import Route, Redirect, RouteProps from 'react-router-dom';
interface PrivateRouteProps extends RouteProps
component: any;
isSignedIn: boolean;
const PrivateRoute = (props: PrivateRouteProps) =>
const component: Component, isSignedIn, ...rest = props;
return (
<Route
...rest
render=(routeProps) =>
isSignedIn ? (
<Component ...routeProps />
) : (
<Redirect
to=
pathname: '/wallet/login',
state: from: routeProps.location
/>
)
/>
);
;
export default PrivateRoute;
JWTContext.tsx(My Context provider):
import React from 'react';
import JWTBody, JWTHeader, JWTToken from "../interfaces/JWTToken"
export interface JWTContext null): void;
isValid(): Promise<boolean>;
updateFromLocalStorage(): (JWTToken
export const jWTContextInitialState : JWTContext =
jWTToken: initFromLocalStorage(),
setJWTToken: (jWTToken) =>
jWTContextInitialState.jWTToken = jWTToken;
,
isValid: async() =>
if (jWTContextInitialState.jWTToken)
let response = await fetch("/auth/tokenvalid",
method: "GET",
headers:
"Content-Type": "application/json",
"Authorization": JSON.stringify(jWTContextInitialState.jWTToken));
let res = await response.json();
if (res.code === 200)
return true;
return false;
,
updateFromLocalStorage: () =>
return initFromLocalStorage()
;
function initFromLocalStorage()
let localStorageToken = localStorage.getItem("velonaJWT");
if (localStorageToken)
return parseJwt(localStorageToken);
return null;
function parseJwt (token: string): JWTToken
token = token.replace("Bearer ", "");
let tokenArray = token.split('.');
let header = tokenArray[0];
header = header.replace('-', '+').replace('_', '/');
let bufferHeader = Buffer.from(header, "base64");
let dataHeader: JWTHeader = JSON.parse(bufferHeader.toString());
let body = tokenArray[1];
body = body.replace('-', '+').replace('_', '/');
let bufferBody = Buffer.from(body, "base64");
let dataBody: JWTBody = JSON.parse(bufferBody.toString());
return (
header: dataHeader,
body: dataBody,
sig: tokenArray[2]
);
//return JWTToken(JSON.parse(bufferHeader.toString()), JSON.parse(bufferBody.toString()), tokenArray[2])
export const JWTContext = React.createContext(jWTContextInitialState);
and finally the (JWTToken.tsx -> just for interfaces)
// represent velona WJT token
export interface JWTToken
header: JWTHeader,
body: JWTBody,
sig: string,
export interface JWTHeader
typ: string,
alg: string
export interface JWTBody
sub: number,
jti: string,
authorities: Authorities[],
iat: number,
nbf: number,
exp: number,
environment: string
export enum Authorities
ROLE_USER,
ROLE_TRUSTEE,
ROLE_EMPLOYEE,
ROLE_ADMIN
reactjs typescript react-router-v4 react-hooks
reactjs typescript react-router-v4 react-hooks
asked yesterday
Roie BeckRoie Beck
6817
6817
Does it work if you as an experiment change the logged in state touseState(true)
?
– Tholle
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
1
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday
add a comment |
Does it work if you as an experiment change the logged in state touseState(true)
?
– Tholle
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
1
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday
Does it work if you as an experiment change the logged in state to
useState(true)
?– Tholle
yesterday
Does it work if you as an experiment change the logged in state to
useState(true)
?– Tholle
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
1
1
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday
add a comment |
1 Answer
1
active
oldest
votes
@Tholle helped me understand the issue,
because at first the user is not authenticated(until JWT is authed by the server -> async) we need to add the following in the react dom Switch:
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
/*all other private routes here*/
isLoggedIn ? <Redirect to="/wallet/portfolio"/> : ""
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
of course the downside is that if user is logged in he will not be able to go to any public page(like registration), but I can live with that...
thanks @Tholle
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023221%2freact-router-dom-with-react-hooks-does-not-redirect-to-correct-route%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
@Tholle helped me understand the issue,
because at first the user is not authenticated(until JWT is authed by the server -> async) we need to add the following in the react dom Switch:
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
/*all other private routes here*/
isLoggedIn ? <Redirect to="/wallet/portfolio"/> : ""
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
of course the downside is that if user is logged in he will not be able to go to any public page(like registration), but I can live with that...
thanks @Tholle
add a comment |
@Tholle helped me understand the issue,
because at first the user is not authenticated(until JWT is authed by the server -> async) we need to add the following in the react dom Switch:
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
/*all other private routes here*/
isLoggedIn ? <Redirect to="/wallet/portfolio"/> : ""
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
of course the downside is that if user is logged in he will not be able to go to any public page(like registration), but I can live with that...
thanks @Tholle
add a comment |
@Tholle helped me understand the issue,
because at first the user is not authenticated(until JWT is authed by the server -> async) we need to add the following in the react dom Switch:
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
/*all other private routes here*/
isLoggedIn ? <Redirect to="/wallet/portfolio"/> : ""
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
of course the downside is that if user is logged in he will not be able to go to any public page(like registration), but I can live with that...
thanks @Tholle
@Tholle helped me understand the issue,
because at first the user is not authenticated(until JWT is authed by the server -> async) we need to add the following in the react dom Switch:
<BrowserRouter>
<Switch>
<PrivateRoute exact path="/wallet/portfolio" component=AppPortfolio isSignedIn=isLoggedIn/>
/*all other private routes here*/
isLoggedIn ? <Redirect to="/wallet/portfolio"/> : ""
<Route exact path="/wallet/login" component=AppLogin />
<Route exact path="/wallet/register" component=AppRegister />
<Redirect to=isLoggedIn ? "/wallet/portfolio" : "/wallet/login"/>
</Switch>
</BrowserRouter>
of course the downside is that if user is logged in he will not be able to go to any public page(like registration), but I can live with that...
thanks @Tholle
answered yesterday
Roie BeckRoie Beck
6817
6817
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55023221%2freact-router-dom-with-react-hooks-does-not-redirect-to-correct-route%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Does it work if you as an experiment change the logged in state to
useState(true)
?– Tholle
yesterday
@Tholle , yes, it does when setting : isSignedIn=true , it works, But I have tested the useEffect and made sure when the isValid() function return that the components is re-render
– Roie Beck
yesterday
1
@Tholle, that help me figure out the issue, because at the beginning I am not logged in after it is redirecting me to /wallet/login i need to check this first: isLoggedIn ? <Redirect to="/wallet/portfolio"/> : "" only if the user is not logged in can I continue to redirect or register
– Roie Beck
yesterday