I want to make a redirection in axios interceptors when receiving a 403 error. But how can I access the history outside React components ?
In Navigating Programatically
I solved this task by creating browser history from history (https://github.com/ReactTraining/history) package and passing it into the interceptor function and then calling .push() method from it.
The main file code (part of it):
// app.js
import { createBrowserHistory } from 'history';
import httpService from './api_client/interceptors';
...
const history = createBrowserHistory();
httpService.setupInterceptors(store, history);
Interceptor configuration:
import axios from 'axios';
export default {
setupInterceptors: (store, history) => {
axios.interceptors.response.use(response => {
return response;
}, error => {
if (error.response.status === 401) {
store.dispatch(logoutUser());
}
if (error.response.status === 404) {
history.push('/not-found');
}
return Promise.reject(error);
});
},
};
Also, you should use Router from react-router (https://github.com/ReactTraining/react-router) and pass the same history object as history param.
// app.js
...
ReactDOM.render(
...
, document.getElementById('#root'))