title: How do you use react-router-dom to redirect user when token has expired?
body: <p>I have a React application that accesses a Flask API. To access some API routes, the user needs to log in. I am using Axios to do the requests. Then, he receives a token which is stored in the local storage. When this token expires and the user makes another request, I want to <strong>redirect him to the login page</strong>. However, I don't know how I would do it.</p>
  <p>I am treating API request errors with <strong>Axios response interceptor</strong>. It removes the token from the local storage and then should redirect the user to the login page. Since I am using <strong>functional components</strong>, I could not find an example that fits well (besides downloading another package called history).</p>
  <p>I have tried to use the 'useHistory' hook and Redirect from react-router-dom (with a proper BrowserRouter set up), but it doesn't work.</p>
  <p><strong>api.js</strong></p>
  <pre><code>import axios from &quot;axios&quot;
  
  import { RemoveAuth } from &quot;./Auth&quot;
  
  export const api = axios.create({
      baseURL: &quot;http://localhost:5000/api/&quot;,
      timeout: 15000,
  })
  
  // more code
  
  api.interceptors.response.use(null, (error) =&gt; {
  
    if(error.response.status === 401){
      RemoveAuth();
    }
  
    return error;
  });
  
  </code></pre>
  <p><strong>Auth.js</strong></p>
  <pre><code>import { useHistory } from &quot;react-router-dom&quot;
  
  export const RemoveAuth = () =&gt; {
    let history = useHistory()
    localStorage.clear();
    history.push('/login')
  }
  </code></pre>
  <p><strong>routes.js</strong></p>
  <pre><code>import React from &quot;react&quot;;
  
  import { BrowserRouter, Switch, Route } from &quot;react-router-dom&quot;;
  
  import PrivateRoutes from &quot;./PrivateRoutes&quot;;
  
  
  import Dashboard from &quot;../pages/dashboard&quot;;
  
  import Login from &quot;../pages/login&quot;;
  import Logout from &quot;../pages/logout&quot;;
  
  const Routes = () =&gt; (
    &lt;BrowserRouter&gt;
      &lt;Switch&gt;
        &lt;PrivateRoutes exact path=&quot;/dashboard&quot; component={Dashboard} /&gt;
        &lt;PrivateRoutes exact path=&quot;/logout&quot; component={Logout} /&gt;
        &lt;Route exact path=&quot;/login&quot; component={Login} /&gt;
      &lt;/Switch&gt;
    &lt;/BrowserRouter&gt;
  );
  </code></pre>
  <p><strong>PrivateRoutes.js</strong></p>
  <pre><code>import React from &quot;react&quot;;
  
  import { Route, Redirect } from &quot;react-router-dom&quot;;
  
  import { AuthLogin } from &quot;../services/Auth&quot;;
  
  const PrivateRoutes = ({ component: Component, ...rest }) =&gt; (
      &lt;Route
        {...rest}
        render={() =&gt; (AuthLogin() ? &lt;Redirect to=&quot;/login&quot; /&gt; : &lt;Component /&gt;)}
      /&gt;
  );
  
  export default PrivateRoutes;
  </code></pre>
  <p>Thanks in advance for the help!</p>