Search code examples
reactjsreact-routeraxiosinterceptor

How to write redirection inside the axios interceptors without reloading in React JS


I used axios interceptors to maintain the internal server errors. I need to redirect to another url if the response have an error without reloading. Below code I used location.href. So it's reloading. I need a solution to redirect without refreshing the page.

I tried "Redirect" in react-router-dom. But it not works for me.

export function getAxiosInstance() {
    const instance = axios.create();
    const token    = getJwtToken();

    // Set the request authentication header
    instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;

    // Set intercepters for response
    instance.interceptors.response.use(
        (response) => response,
        (error) => {
            if (config.statusCode.errorCodes.includes(error.response.status)) {
                return window.location.href = '/internal-server-error';
            }

            return window.location.href = '/login';
        }
    );

    return instance;
}

Can anyone help me to solve this out?


Solution

  • This will take advantage of import caching:

    // history.js
    import { createBrowserHistory } from 'history'
    
    export default createBrowserHistory({
      /* pass a configuration object here if needed */
    })
    
    
    // index.js (example)
    import { Router } from 'react-router-dom'
    import history from './history'
    import App from './App'
    
    ReactDOM.render((
      <Router history={history}>
        <App />
      </Router>
    ), holder)
    
    
    // interceptor.js
    import axios from 'axios';
    import cookie from 'cookie-machine';
    import history from '../history';
    
    axios.interceptors.response.use(null, function(err) {
      if ( err.status === 401 ) {
        cookie.remove('my-token-key');
        history.push('/login');
      }
    
      return Promise.reject(err);
    });