Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.3 kB
2
Indexable
Never
// 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