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










0















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










share|improve this question






















  • 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















0















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










share|improve this question






















  • 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













0












0








0








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










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked yesterday









Roie BeckRoie Beck

6817




6817












  • 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

















  • 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
















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












1 Answer
1






active

oldest

votes


















0














@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






share|improve this answer






















    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
    );



    );













    draft saved

    draft discarded


















    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









    0














    @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






    share|improve this answer



























      0














      @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






      share|improve this answer

























        0












        0








        0







        @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






        share|improve this answer













        @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







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Roie BeckRoie Beck

        6817




        6817





























            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme