Untitled
// AxiosInterceptorProvider.js import React, { createContext, useContext, useEffect } from 'react'; import api from './api'; import { useTranslation } from 'react-i18next'; const AxiosInterceptorContext = createContext(null); export const AxiosInterceptorProvider = ({ children }) => { const { t } = useTranslation(); // Use your hook here useEffect(() => { const responseInterceptor = api.interceptors.response.use( response => { // Example: Adding a translation to the response data response.data.message = t(response.data.messageKey); return response; }, error => { // Example: Handle error translations if (error.response && error.response.data) { error.response.data.errorMessage = t(error.response.data.errorKey); } return Promise.reject(error); } ); // Cleanup function to remove interceptor when component unmounts return () => { api.interceptors.response.eject(responseInterceptor); }; }, [t]); // Dependency array to re-run if `t` changes return ( <AxiosInterceptorContext.Provider value={null}> {children} </AxiosInterceptorContext.Provider> ); }; export const useAxiosInterceptor = () => useContext(AxiosInterceptorContext);
Leave a Comment