Implementing PrivateRoute in React.js










0














I'm having some problems with implementing PrivateRoute in React. Here is my code:



class App extends Component 

constructor(props)
super(props);

this.state =
currentUser: null,
loadingUser: true



componentDidMount()
this.onAuth();
;

onAuth = () =>
getCurrentUser().then((json) =>
console.log(json);
this.setState(
currentUser: json,
loadingUser: false
)
).catch((error) =>
this.setState(
currentUser: null,
loadingUser: false,
)
)
;

logout = () =>
logout();
this.setState(
currentUser: null,
loadingUser: false
);
this.props.history.push("/");
toast.info("Succesfully logout.");
;

render()

return (
<div className="body">
<ToastContainer closeOnClick=false/>
<ApplicationHeader currentUser=this.state.currentUser logout=this.logout/>
<Grid>
<div className="app-content">
<Switch>
<Route exact path="/vote/:id" render=(props) => <Vote currentUser=this.state.currentUser ...props/>/>

<Route exact path="/login" render=() => <Login onAuth=this.onAuth />/>

<PrivateRoute authed=this.state.currentUser != null exact path="/vote" component=NewProcess />
<PrivateRoute authed=this.state.currentUser != null exact path="/items" component=NewItems />

<Route component=NotFound/>


</Switch>
</div>
</Grid>
<Footer/>
</div>

);



const PrivateRoute = (component: Component, authed, ...rest) =>
return (
<Route
...rest
render=(props) => authed === true
? <Component ...props />
: <Redirect to=pathname: '/login', state: from: props.location /> />
)



When user posts credentials (or App main component gets rendered) onAuth method gets invoked and sets (or not) currentUser property of App's state. This property is null (when user is not authenticated) and represents userdetails such like id and username (when user is authenticated). Then, in PrivateRoute based on that property component gets rendered or application redirects user back to the login page. And that doesn't work well. I mean when i'm already authenticated and try to access any of private route, i am redirected to proper component. Problem occurs in 2 situations:



  1. right after logging in - application doesnt redirect me to component
    i want to access, insted i stay on the login page.

  2. refreshing page (in browser) corresponded to private route.

It seems like PrivateRoute component doesnt get refreshed when currentUser property gets changed, which is kinda weird because i'm using similar approach in ApplicationHeader to display username when user is authenticated (and that is refreshed correctly).
So, what am i doing wrong here?










share|improve this question


























    0














    I'm having some problems with implementing PrivateRoute in React. Here is my code:



    class App extends Component 

    constructor(props)
    super(props);

    this.state =
    currentUser: null,
    loadingUser: true



    componentDidMount()
    this.onAuth();
    ;

    onAuth = () =>
    getCurrentUser().then((json) =>
    console.log(json);
    this.setState(
    currentUser: json,
    loadingUser: false
    )
    ).catch((error) =>
    this.setState(
    currentUser: null,
    loadingUser: false,
    )
    )
    ;

    logout = () =>
    logout();
    this.setState(
    currentUser: null,
    loadingUser: false
    );
    this.props.history.push("/");
    toast.info("Succesfully logout.");
    ;

    render()

    return (
    <div className="body">
    <ToastContainer closeOnClick=false/>
    <ApplicationHeader currentUser=this.state.currentUser logout=this.logout/>
    <Grid>
    <div className="app-content">
    <Switch>
    <Route exact path="/vote/:id" render=(props) => <Vote currentUser=this.state.currentUser ...props/>/>

    <Route exact path="/login" render=() => <Login onAuth=this.onAuth />/>

    <PrivateRoute authed=this.state.currentUser != null exact path="/vote" component=NewProcess />
    <PrivateRoute authed=this.state.currentUser != null exact path="/items" component=NewItems />

    <Route component=NotFound/>


    </Switch>
    </div>
    </Grid>
    <Footer/>
    </div>

    );



    const PrivateRoute = (component: Component, authed, ...rest) =>
    return (
    <Route
    ...rest
    render=(props) => authed === true
    ? <Component ...props />
    : <Redirect to=pathname: '/login', state: from: props.location /> />
    )



    When user posts credentials (or App main component gets rendered) onAuth method gets invoked and sets (or not) currentUser property of App's state. This property is null (when user is not authenticated) and represents userdetails such like id and username (when user is authenticated). Then, in PrivateRoute based on that property component gets rendered or application redirects user back to the login page. And that doesn't work well. I mean when i'm already authenticated and try to access any of private route, i am redirected to proper component. Problem occurs in 2 situations:



    1. right after logging in - application doesnt redirect me to component
      i want to access, insted i stay on the login page.

    2. refreshing page (in browser) corresponded to private route.

    It seems like PrivateRoute component doesnt get refreshed when currentUser property gets changed, which is kinda weird because i'm using similar approach in ApplicationHeader to display username when user is authenticated (and that is refreshed correctly).
    So, what am i doing wrong here?










    share|improve this question
























      0












      0








      0







      I'm having some problems with implementing PrivateRoute in React. Here is my code:



      class App extends Component 

      constructor(props)
      super(props);

      this.state =
      currentUser: null,
      loadingUser: true



      componentDidMount()
      this.onAuth();
      ;

      onAuth = () =>
      getCurrentUser().then((json) =>
      console.log(json);
      this.setState(
      currentUser: json,
      loadingUser: false
      )
      ).catch((error) =>
      this.setState(
      currentUser: null,
      loadingUser: false,
      )
      )
      ;

      logout = () =>
      logout();
      this.setState(
      currentUser: null,
      loadingUser: false
      );
      this.props.history.push("/");
      toast.info("Succesfully logout.");
      ;

      render()

      return (
      <div className="body">
      <ToastContainer closeOnClick=false/>
      <ApplicationHeader currentUser=this.state.currentUser logout=this.logout/>
      <Grid>
      <div className="app-content">
      <Switch>
      <Route exact path="/vote/:id" render=(props) => <Vote currentUser=this.state.currentUser ...props/>/>

      <Route exact path="/login" render=() => <Login onAuth=this.onAuth />/>

      <PrivateRoute authed=this.state.currentUser != null exact path="/vote" component=NewProcess />
      <PrivateRoute authed=this.state.currentUser != null exact path="/items" component=NewItems />

      <Route component=NotFound/>


      </Switch>
      </div>
      </Grid>
      <Footer/>
      </div>

      );



      const PrivateRoute = (component: Component, authed, ...rest) =>
      return (
      <Route
      ...rest
      render=(props) => authed === true
      ? <Component ...props />
      : <Redirect to=pathname: '/login', state: from: props.location /> />
      )



      When user posts credentials (or App main component gets rendered) onAuth method gets invoked and sets (or not) currentUser property of App's state. This property is null (when user is not authenticated) and represents userdetails such like id and username (when user is authenticated). Then, in PrivateRoute based on that property component gets rendered or application redirects user back to the login page. And that doesn't work well. I mean when i'm already authenticated and try to access any of private route, i am redirected to proper component. Problem occurs in 2 situations:



      1. right after logging in - application doesnt redirect me to component
        i want to access, insted i stay on the login page.

      2. refreshing page (in browser) corresponded to private route.

      It seems like PrivateRoute component doesnt get refreshed when currentUser property gets changed, which is kinda weird because i'm using similar approach in ApplicationHeader to display username when user is authenticated (and that is refreshed correctly).
      So, what am i doing wrong here?










      share|improve this question













      I'm having some problems with implementing PrivateRoute in React. Here is my code:



      class App extends Component 

      constructor(props)
      super(props);

      this.state =
      currentUser: null,
      loadingUser: true



      componentDidMount()
      this.onAuth();
      ;

      onAuth = () =>
      getCurrentUser().then((json) =>
      console.log(json);
      this.setState(
      currentUser: json,
      loadingUser: false
      )
      ).catch((error) =>
      this.setState(
      currentUser: null,
      loadingUser: false,
      )
      )
      ;

      logout = () =>
      logout();
      this.setState(
      currentUser: null,
      loadingUser: false
      );
      this.props.history.push("/");
      toast.info("Succesfully logout.");
      ;

      render()

      return (
      <div className="body">
      <ToastContainer closeOnClick=false/>
      <ApplicationHeader currentUser=this.state.currentUser logout=this.logout/>
      <Grid>
      <div className="app-content">
      <Switch>
      <Route exact path="/vote/:id" render=(props) => <Vote currentUser=this.state.currentUser ...props/>/>

      <Route exact path="/login" render=() => <Login onAuth=this.onAuth />/>

      <PrivateRoute authed=this.state.currentUser != null exact path="/vote" component=NewProcess />
      <PrivateRoute authed=this.state.currentUser != null exact path="/items" component=NewItems />

      <Route component=NotFound/>


      </Switch>
      </div>
      </Grid>
      <Footer/>
      </div>

      );



      const PrivateRoute = (component: Component, authed, ...rest) =>
      return (
      <Route
      ...rest
      render=(props) => authed === true
      ? <Component ...props />
      : <Redirect to=pathname: '/login', state: from: props.location /> />
      )



      When user posts credentials (or App main component gets rendered) onAuth method gets invoked and sets (or not) currentUser property of App's state. This property is null (when user is not authenticated) and represents userdetails such like id and username (when user is authenticated). Then, in PrivateRoute based on that property component gets rendered or application redirects user back to the login page. And that doesn't work well. I mean when i'm already authenticated and try to access any of private route, i am redirected to proper component. Problem occurs in 2 situations:



      1. right after logging in - application doesnt redirect me to component
        i want to access, insted i stay on the login page.

      2. refreshing page (in browser) corresponded to private route.

      It seems like PrivateRoute component doesnt get refreshed when currentUser property gets changed, which is kinda weird because i'm using similar approach in ApplicationHeader to display username when user is authenticated (and that is refreshed correctly).
      So, what am i doing wrong here?







      javascript reactjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 at 14:15









      peter Schiza

      74113




      74113






















          1 Answer
          1






          active

          oldest

          votes


















          0














          I did it rendering the route or the redirect depending on the condition and it worked for me.



          Something like the following:



           class PrivateRouteComponent extends React.Component

          render()
          return (
          this.props.isAuthenticated===true?
          (
          <Route path=this.props.path render=this.props.component />
          ):
          (<Redirect to=
          pathname: '/login',
          state: from: this.props.path
          />));







          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%2f53264027%2fimplementing-privateroute-in-react-js%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














            I did it rendering the route or the redirect depending on the condition and it worked for me.



            Something like the following:



             class PrivateRouteComponent extends React.Component

            render()
            return (
            this.props.isAuthenticated===true?
            (
            <Route path=this.props.path render=this.props.component />
            ):
            (<Redirect to=
            pathname: '/login',
            state: from: this.props.path
            />));







            share|improve this answer

























              0














              I did it rendering the route or the redirect depending on the condition and it worked for me.



              Something like the following:



               class PrivateRouteComponent extends React.Component

              render()
              return (
              this.props.isAuthenticated===true?
              (
              <Route path=this.props.path render=this.props.component />
              ):
              (<Redirect to=
              pathname: '/login',
              state: from: this.props.path
              />));







              share|improve this answer























                0












                0








                0






                I did it rendering the route or the redirect depending on the condition and it worked for me.



                Something like the following:



                 class PrivateRouteComponent extends React.Component

                render()
                return (
                this.props.isAuthenticated===true?
                (
                <Route path=this.props.path render=this.props.component />
                ):
                (<Redirect to=
                pathname: '/login',
                state: from: this.props.path
                />));







                share|improve this answer












                I did it rendering the route or the redirect depending on the condition and it worked for me.



                Something like the following:



                 class PrivateRouteComponent extends React.Component

                render()
                return (
                this.props.isAuthenticated===true?
                (
                <Route path=this.props.path render=this.props.component />
                ):
                (<Redirect to=
                pathname: '/login',
                state: from: this.props.path
                />));








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 at 14:36









                jmtalarn

                7551712




                7551712



























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53264027%2fimplementing-privateroute-in-react-js%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







                    這個網誌中的熱門文章

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    Node.js Script on GitHub Pages or Amazon S3

                    Museum of Modern and Contemporary Art of Trento and Rovereto