2

I have an axios interceptors and when a user gets forced logged out(because of expired token) I want to go back to my home page.

I am not sure how to pass react router to it though. I am using mobx but not sure if that will help me with this problem.

export const axiosInstance = axios.create({
    baseURL: 'https://localhost:44391/api',
    timeout: 5000,
    contentType: "application/json",
    Authorization: getAuthToken()
  })

  axiosInstance.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    const originalRequest = error.config;
    if(error.code != "ECONNABORTED" && error.response.status === 401 && !originalRequest._retry){
      originalRequest._retry = true;
      return axiosInstance.post("/tokens/auth",{
        "refreshToken": getRefreshToken(),
        "grantType": "refresh_token"
    }).then(response => {
        localStorage.authentication = JSON.stringify(response.data);
        updateAuthInstant();
        return axiosInstance(originalRequest)
      });

    }
   return Promise.reject(error);
  });
chobo2
  • 83,322
  • 195
  • 530
  • 832
  • do you need to make any ajax calls that could redirect before you render your top level component? – azium Jul 17 '18 at 19:12
  • I am not sure what you mean, the most common scenario would be that a request is sent, the users access token is expired, a refresh token attempt is tried to be used. If that fails, kick them back to login page. – chobo2 Jul 17 '18 at 19:17

2 Answers2

5

You should add the history npm package. With this you can create the browser history and use this within other places of your application.

For example:

// routing.js

import createHistory from 'history/createBrowserHistory';

export const history = createHistory();

In your component that contains your routes.

import { Route, Router } from 'react-router-dom';
import { history } from './routing.js';

import ComponentA from './ComponentA';
import ComponentB from './ComponentB';

const Routes = () => (
  <Router history={history}>
    <div>
      <Route exact path='/route1' component={ComponentA} />
      <Route exact path='/route2' component={ComponentB} />
    </div>
  </Router>
);

And in your other file in which you want to control the routing:

import { history } from './routing.js';

function changeRoute() {
  // things happening here..
  history.push('/route2');
} 

When calling changeRoute() the path is updated to /route2 and ComponentB will be rendered.

Alserda
  • 4,246
  • 1
  • 17
  • 25
  • Ah, I am using createBrowserHistory already never thought of putting it in it's own file like that though. Was using it to populate my stores like this const browserHistory = createBrowserHistory(); const history = syncHistoryWithStore(browserHistory, routingStore); Just quick question on that though. Is there a difference between {history} & {browserHistory} – chobo2 Jul 17 '18 at 20:17
  • `browserHistory` was part of react-router 2 and 3. In react-router 4 this is combined as [BrowserRouter](https://reacttraining.com/react-router/web/api/BrowserRouter). This is for basic history-API usage. If you create the browserHistory yourself, you can do stuff like this :-). – Alserda Jul 17 '18 at 20:23
  • Should I switch to createHistory() then instead of createBrowserHistory() – chobo2 Jul 17 '18 at 21:00
  • I don't think I understand what you mean. Are you refering at my way of importing in the routing.js example? In that example I name the `createBrowserHistory` function that I'm importing from the `history` package as `createHistory`. This can be named as anything you want. – Alserda Jul 17 '18 at 21:04
  • Ahhh right, I thought that was the actually like function name but I guess that is the default function that is exported? – chobo2 Jul 17 '18 at 21:09
  • Yes this has to do with the way that the module is exported from the library. They use this importing method on their documentation, but looking at the CommonJS approach I assume that you can also import is like `import { createBrowserHistory } from 'history'` as well (but I haven't tried this out yet). This [chapter about ES6 modules](http://2ality.com/2014/09/es6-modules-final.html) is a pretty good read if you're interested in that. – Alserda Jul 17 '18 at 21:13
0
window.location.href = '/user/login'
N. Haru
  • 11
  • 1