Using Axios interceptors in React applications and integrating them with React Context is an effective approach for managing API requests and responses, particularly when handling global state management (such as authentication state). I will guide you through the steps to correctly implement this structure.
Step 1: Create Axios Instance
First, let's create an Axios instance to define default configurations, such as the base URL and other common settings.
javascriptimport axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://api.example.com', headers: { 'Content-Type': 'application/json' } });
Step 2: Set Up Axios Interceptors
On the Axios instance, we can configure request interceptors and response interceptors. Request interceptors modify requests before they are sent, for example, by adding an authentication token. Response interceptors handle responses or errors globally.
javascriptaxiosInstance.interceptors.request.use( config => { const token = sessionStorage.getItem('authToken'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); } ); axiosInstance.interceptors.response.use( response => response, error => { // Handle errors, for example, redirect to login if token expires if (error.response.status === 401) { // handle token expiration (e.g., redirect to login) } return Promise.reject(error); } );
Step 3: Create React Context
Next, let's create a React Context to make the Axios instance accessible throughout the application.
javascriptimport React, { createContext } from 'react'; export const AxiosContext = createContext({ axiosInstance }); export const AxiosProvider = ({ children }) => { return ( <AxiosContext.Provider value={{ axiosInstance }}> {children} </AxiosContext.Provider> ); };
Step 4: Use Axios Context in React Components
Now, you can utilize the Axios Context within any React component to make API requests.
javascriptimport React, { useContext } from 'react'; import { AxiosContext } from './AxiosContext'; const MyComponent = () => { const { axiosInstance } = useContext(AxiosContext); const fetchData = async () => { try { const response = await axiosInstance.get('/data'); console.log(response.data); } catch (error) { console.error('Error fetching data', error); } }; return ( <div> <button onClick={fetchData}>Fetch Data</button> </div> ); } export default MyComponent;
Conclusion
By implementing this approach, we not only configure Axios interceptors for handling requests and responses but also leverage React Context to ensure the Axios instance is accessible across the application. This is especially critical for managing requests and responses that require global state (e.g., authentication state). This structure enhances code modularity and maintainability.