title: React Router Private Route Async Use Effect
body: <p>Basically, I am facing an issue where my route doesn't work correctly if someone were to delete the cookies.  I am using Auth0 and React Router.</p>
  
  <p>What I can't figure out is why it is skipping the if statement.  No idea why that wouldn't be hit and then that would redirect to login instead.</p>
  
  <p>Debug code:</p>
  
  <p><a href="https://i.stack.imgur.com/YVJ0D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YVJ0D.png" alt="enter image description here"></a></p>
  
  <p>Actual code for reference:</p>
  
  <pre><code>import React, { useEffect } from "react";
  import history from "../history";
  import { Route } from "react-router-dom";
  import { useAuth0 } from '../auth/Auth';
  
  const PrivateRoute = ({ component: Component, path, ...rest }) =&gt; {
  debugger;
    const { authenticated } = useAuth0();
    useEffect(() =&gt; {
      const fn = async () =&gt; {
        console.log("authenticated", authenticated)
        if (!authenticated || authenticated === null) {
          history.replace('/login');
        }
      };
      fn();
    }, [authenticated, path]);
  
    const render = props =&gt; &lt;Component {...props} /&gt;;
  
    return &lt;Route path={path} render={render} {...rest} /&gt;;
  };
  
  export default PrivateRoute;
  </code></pre>
  
  <p>Here is a slimmed down version of my App.js</p>
  
  <pre><code>import React, { useEffect } from "react";
  import './App.scss';
  import { Router, Route, Switch } from "react-router-dom";
  import { Redirect } from "react-router";
  import history from "./history";
  import Home from "./scenes/Home/Home";
  import Profile from "./scenes/Profile/Profile";
  import SignUp from "./scenes/SignUp/SignUp";
  import Login from "./scenes/SignUp/Login/Login";
  import Dashboard from "./scenes/Dashboard/Dashboard";
  import Account from "./scenes/Account/Account";
  import Auth0Callback from "./scenes/Auth0Callback/Auth0Callback";
  import { useAuth0 } from "./auth/Auth";
  import PrivateRoute from "./components/PrivateRoute";
  
  import PrivateRouteAuth from "./components/PrivateRouteAuth";
  import NavBarMain from "./components/NavBarMain/NavBarMain";
  import NavBarBasic from "./components/NavBarBasic/NavBarBasic";
  import Footer from "./components/Footer/Footer";
  import ScrollToTop from "./ScrollToTop";
  
  // private route for main part of application
  const NavRoute = ({ exact, path, component: Component }) =&gt; (
    &lt;PrivateRoute
      exact={exact}
      path={path} render={(props) =&gt; (
        &lt;&gt;
          &lt;NavBarMain /&gt;
          &lt;Component {...props} /&gt;
          &lt;Footer /&gt;
        &lt;/&gt;
      )} /&gt;
  )
  
  // private route for signup since need basic navbar
  const NavRouteSignUp = ({ exact, path, component: Component }) =&gt;
    (
      &lt;PrivateRouteAuth
        exact={exact}
        path={path} render={(props) =&gt;
          (
            &lt;&gt;
              &lt;NavBarBasic /&gt;
              &lt;Component {...props} /&gt;
              &lt;Footer /&gt;
            &lt;/&gt;
          )} /&gt;
    )
  
  function App() {
  
    const { renewSession, authenticated } = useAuth0();
    useEffect(() =&gt; {
      if (localStorage.getItem("auth") === "true") {
        renewSession();
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
  
  
    return (
      &lt;div className="App"&gt;
        &lt;Router history={history}&gt;
          &lt;ScrollToTop&gt;
            &lt;Switch&gt;
              &lt;Route exact path="/" render={() =&gt; (
                authenticated ? (
                  &lt;Route path="/" exact component={Home} /&gt; 
                ) : (
                  &lt;Redirect to="/login" /&gt;
                  )
              )} /&gt;
              {authenticated ? &lt;NavRouteSignUp path="/signup" exact component={SignUp} /&gt; : &lt;NavRouteBase path="/signup" exact component={SignUp} /&gt;}
              {authenticated ? &lt;NavRouteSignUp path="/login" exact component={Login} /&gt; : &lt;NavRouteBase path="/login" exact component={Login} styleName="noBorder" /&gt;}
              &lt;Route path="/callback" render={(props) =&gt; {
                return &lt;Auth0Callback {...props} /&gt;
              }} /&gt;
              &lt;NavRoute exact component={Dashboard} path="/progress" /&gt;
              &lt;NavRoute exact component={Profile} path="/profile" /&gt;
              &lt;NavRoute exact component={Account} path="/account" /&gt;
            &lt;/Switch&gt;
          &lt;/ScrollToTop&gt;
        &lt;/Router&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>
  
  <p>And my Auth.js relevant to updating the session:</p>
  
  <pre><code>// logoout method removes all id's from local storage
    const logout = () =&gt; {
      console.log("the user is logging out");
      // Remove tokens and expiry time
      localStorage.removeItem('access_token')
      localStorage.removeItem('id_token')
      localStorage.removeItem('expires_at')
      localStorage.removeItem('user')
      localStorage.removeItem('auth')
      localStorage.removeItem('selection')
      setAuthenticated(null);
      setUser(null);
      history.push('/')
    }
  
  
    // method called once callback initiated
    const handleAuthentication = () =&gt; {
      console.log("auth0Client", auth0Client);
      if (typeof window !== 'undefined') {
        auth0Client.parseHash(async (err, authResult) =&gt; {
          if (authResult &amp;&amp; authResult.accessToken &amp;&amp; authResult.idToken) {
            console.log('inside the if authResult')
            await setSession(authResult);
            await howFarAlongIsUser();
          } else if (err) {
            console.log(err)
            return err;
          }
        })
      }
    }
  
    const isAuthenticated = () =&gt; {
      if (typeof localStorage !== 'undefined') {
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'))
        // setAuthenticated(true);
        return new Date().getTime() &lt; expiresAt
      } else {
        localStorage.setItem('auth', false)
        return false
      }
    }
  
    const setSession = async authResult =&gt; {
      const expiresAt = JSON.stringify(
        authResult.expiresIn * 1000 + new Date().getTime()
      )
      localStorage.setItem('access_token', authResult.accessToken)
      localStorage.setItem('id_token', authResult.idToken)
      localStorage.setItem('expires_at', expiresAt)
      localStorage.setItem('auth', true)
  
      setAuthenticated(true);
      await new Bluebird(function (resolve, reject) {
        auth0Client.client.userInfo(authResult.accessToken, (err, user) =&gt; {
          if (err) return reject(err)
          return resolve(user);
        })
      }).then(
        data =&gt; {
          localStorage.setItem('user', JSON.stringify(data))
          setUser(data);
          setAuthenticated(true);
        }
      )
    }
  
    const renewSession = async () =&gt; {
  
      auth0Client.checkSession({}, async (err, authResult) =&gt; {
        console.log("AUTH RESULT", authResult);
        if (authResult &amp;&amp; authResult.accessToken &amp;&amp; authResult.idToken) {
          await setSession(authResult);
        } else if (err) {
          console.log("loggin out inside renew session");
          console.log("error", err);
          logout();
        }
      });
    }
  
  const getUser = () =&gt; {
      if (localStorage.getItem('user')) {
        return JSON.parse(localStorage.getItem('user'))
      }
    }
  </code></pre>