To perform redirection from Axios interceptors in React Router V4, follow these steps:
Step 1: Create a new history instance
First, create a history object that can be used throughout your application. This is because Axios interceptors are standard JavaScript modules that are not directly integrated into the React component lifecycle. Typically, you can use the history library to create an independent history object.
javascript// history.js import { createBrowserHistory } from 'history'; export default createBrowserHistory();
Step 2: Pass custom history when using Router
In your React application, initialize the Router with the newly created history instance.
javascript// App.js import { Router } from 'react-router-dom'; import history from './history'; function App() { return ( <Router history={history}> {/* Other parts of the application */} </Router> ); }
Step 3: Use history in Axios interceptors for redirection
Now, import the history object in the Axios interceptors and invoke history.push or history.replace as needed to change the route.
javascript// axios.js import axios from 'axios'; import history from './history'; axios.interceptors.response.use(response => { return response; }, error => { if (error.response.status === 401) { // Assume 401 status code requires redirect to login page history.push('/login'); } return Promise.reject(error); } );
Example: Redirect to login page
Suppose your application needs to redirect users to the login page when authentication fails (e.g., receiving an HTTP 401 error). You can check the error status code in the Axios interceptors and use the history object to redirect the user.
These steps demonstrate how to combine Axios interceptors and the history object in React Router V4 to handle application-level redirection. The benefit is that you can easily redirect users from any part of the application, not just within React components.