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
The best solution I found is to define axios.interceptors inside my main React components and use that
to handle errors :
( And with withRouter
from Router V4 )
import {withRouter} from 'react-router-dom';
class Homepage extends Component {
static propTypes = {
history: PropTypes.object.isRequired
}
constructor(props){
super(props);
let that = this;
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
if(error.response.status === 403) { that.handle403() }
// Trow errr again (may be need for some other catch)
return Promise.reject(error);
});
}
handle403(){
this.props.history.push('/login');
}