如何访问Axios Interceptor中的UseContext

发布于 2025-02-07 04:09:35 字数 2717 浏览 1 评论 0原文

我创建了一个Axios实例和notificationContext用于React WebApp中的使用。 我想访问addnotification在创建Axios实例的request> request> replections interceptor内的函数,但由于这不是一个反应组件,因此不可能。有没有办法将此创建的Axios实例和拦截器作为React组件制作和使用?

notificationcontext.js

import React, { createContext, useState } from 'react';

const NotificationContext = createContext();

const NotificationProvider = ({ children }) => {
    const [notifications, setNotifications] = useState([]);

    const addNotification = (type, title, description) => {
        const notification = {
            id: Date.now(),
            type,
            title,
            description,
        };

        setNotifications([notification, ...notifications]);
    };

    const removeNotification = (id) => {
        setNotifications(notifications.filter((notification) => notification.id !== id));
    };

    return <NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>{children}</NotificationContext.Provider>;
};

export { NotificationContext, NotificationProvider };

app.js

notification -provider围绕着notificationList consement

const App = () => (
    <BrowserRouter>
        <AuthProvider>
            <NotificationProvider>
                <NotificationList />
                <Router />
            </NotificationProvider>
        </AuthProvider>
    </BrowserRouter>
);

export default App;

apiclient.js

import axios from 'axios';
// import { useContext } from 'react';
// import { NotificationContext } from '../context/NotificationContext';

const apiClient = axios.create({
    baseURL: process.env.REACT_APP_API,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    withCredentials: true,
    timeout: 10000,
});

apiClient.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        return Promise.reject(error);
        // How to access AddNotification here
    },
);

apiClient.interceptors.response.use(
    (response) => {
        return Promise.resolve(response);
    },
    (error) => {
        if (!error.response) {
            // network error
            // console.log('Network error');
            // How to access AddNotification here
        } else {
            const response = error.response.data;
            // How to access AddNotification here
        }

        return Promise.reject(error);
    },
);

export default apiClient;

I have created an Axios instance and a notificationContext to use in a React webapp.
I want to access the addNotification function of the notificationContext inside the request/response interceptor of the created Axios instance but since this is not a React component it's not possible. Is there a way to make and use this created Axios instance and interceptors as a React component?

NotificationContext.js

import React, { createContext, useState } from 'react';

const NotificationContext = createContext();

const NotificationProvider = ({ children }) => {
    const [notifications, setNotifications] = useState([]);

    const addNotification = (type, title, description) => {
        const notification = {
            id: Date.now(),
            type,
            title,
            description,
        };

        setNotifications([notification, ...notifications]);
    };

    const removeNotification = (id) => {
        setNotifications(notifications.filter((notification) => notification.id !== id));
    };

    return <NotificationContext.Provider value={{ notifications, addNotification, removeNotification }}>{children}</NotificationContext.Provider>;
};

export { NotificationContext, NotificationProvider };

App.js

The NotificationProvider is wrapped around the NotificationList component

const App = () => (
    <BrowserRouter>
        <AuthProvider>
            <NotificationProvider>
                <NotificationList />
                <Router />
            </NotificationProvider>
        </AuthProvider>
    </BrowserRouter>
);

export default App;

apiClient.js

import axios from 'axios';
// import { useContext } from 'react';
// import { NotificationContext } from '../context/NotificationContext';

const apiClient = axios.create({
    baseURL: process.env.REACT_APP_API,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    withCredentials: true,
    timeout: 10000,
});

apiClient.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        return Promise.reject(error);
        // How to access AddNotification here
    },
);

apiClient.interceptors.response.use(
    (response) => {
        return Promise.resolve(response);
    },
    (error) => {
        if (!error.response) {
            // network error
            // console.log('Network error');
            // How to access AddNotification here
        } else {
            const response = error.response.data;
            // How to access AddNotification here
        }

        return Promise.reject(error);
    },
);

export default apiClient;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最偏执的依靠 2025-02-14 04:09:35
  1. 您可以导出AXIOS实例
  2. 创建功能组件
  3. 访问USEMEMO示例中的上下文
  4. Init Interceptor

(仅是一个想法):

function Interceptor({children}) { 
  const {addNotification} = useContext(NotificationContext)
  useMemo(() => {
    apiClient.interceptors.response.use(
      (response) => {
      return Promise.resolve(response);
      },
     (error) => {
      if (!error.response) {
         addNotification()
      } else {
        const response = error.response.data;
        addNotification()
      }
      return Promise.reject(error);
      },
   );
  }, [addNotification])
return <>{children}</>
}

app.js

const App = () => (
<BrowserRouter>
    <AuthProvider>
        <NotificationProvider>
            <Interceptor> // here
                <NotificationList />
                <Router />
            <Interceptor />
        </NotificationProvider>
    </AuthProvider>
</BrowserRouter>);

export default App;
  1. You can export the axios instance
  2. create a functional component
  3. access the context
  4. init interceptor in useMemo

Example (just for an idea):

function Interceptor({children}) { 
  const {addNotification} = useContext(NotificationContext)
  useMemo(() => {
    apiClient.interceptors.response.use(
      (response) => {
      return Promise.resolve(response);
      },
     (error) => {
      if (!error.response) {
         addNotification()
      } else {
        const response = error.response.data;
        addNotification()
      }
      return Promise.reject(error);
      },
   );
  }, [addNotification])
return <>{children}</>
}

and in App.js

const App = () => (
<BrowserRouter>
    <AuthProvider>
        <NotificationProvider>
            <Interceptor> // here
                <NotificationList />
                <Router />
            <Interceptor />
        </NotificationProvider>
    </AuthProvider>
</BrowserRouter>);

export default App;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文