简体   繁体   English

在带有导出的自定义 Axios 服务中使用 React Hook

[英]Using react hook in custom Axios service with export

I have a created useAxiosPrivate hook and I want to use it in a service function I have created using axios which I used to export diffrent methods.我有一个创建的 useAxiosPrivate 挂钩,我想在我使用 axios 创建的服务 function 中使用它,我用来导出不同的方法。 But since its not a functional or class component I get an error react hooks must be called in a react function component or a custom react hook function但由于它不是功能性组件或 class 组件,我得到一个错误 react hooks must be called in a react function component or a custom react hook function

useAxiosPrivate.tsx使用AxiosPrivate.tsx

import { axiosPrivate } from '../api/axios'
import { useEffect } from 'react'
import useRefreshToken from './useRefreshToken'
import useAuth from './useAuth'

const useAxiosPrivate = () => {
  const refresh = useRefreshToken()
  const { auth }: any = useAuth()

  useEffect(() => {
    const requestIntercept = axiosPrivate.interceptors.request.use(
      (config) => {
        config.headers = config.headers ?? {}
        if (!config.headers['Authorization']) {
          config.headers['Authorization'] = `Bearer ${auth?.accessToken}`
        }
        return config
      },
      (error) => Promise.reject(error),
    )

    const responseIntercept = axiosPrivate.interceptors.response.use(
      (response) => response,
      async (error) => {
        const prevRequest = error?.config
        if (
          (error?.response?.status === 403 || error?.response?.status === 401) &&
          !prevRequest?.sent
        ) {
          prevRequest.sent = true
          const newAccessToken = await refresh()
          prevRequest.headers['Authorization'] = `Bearer ${newAccessToken}`
          return axiosPrivate(prevRequest)
        }
        return Promise.reject(error)
      },
    )

    return () => {
      axiosPrivate.interceptors.request.eject(requestIntercept)
      axiosPrivate.interceptors.response.eject(responseIntercept)
    }
  }, [auth, refresh])

  return axiosPrivate
}

export default useAxiosPrivate

I want to use this in auth.service.tsx我想在 auth.service.tsx 中使用它

import useAxiosPrivate from "../hooks/useAxiosPrivate"

const axiosPrivate = useAxiosPrivate();  <-- 'I want to use this in this'

export const SharedService {
     

     UpdateProfile: async (firstName:string, lastName:string) => {
         const response = await axiosPrivate.put('/user/me',{
         firstName,
         lastName,
     })


}

I get error that hooks should be used at top level or inside functional component or class how do I fix it?我收到错误消息,指出应在顶层或功能组件内部使用挂钩或 class 我该如何解决?

Your service must be a hook as well so it can use other hooks您的服务也必须是一个钩子,以便它可以使用其他钩子

import useAxiosPrivate from "../hooks/useAxiosPrivate";

export const useSharedService = () => {
  const axiosPrivate = useAxiosPrivate();
  return {
    UpdateProfile: async (firstName: string, lastName: string) => {
      const response = await axiosPrivate.put("/user/me", {
        firstName,
        lastName,
      });
    },
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM