reactjs 在导出的自定义Axios服务中使用react钩子

vql8enpb  于 2022-12-26  发布在  React
关注(0)|答案(1)|浏览(151)

我创建了一个useAxiosPrivate钩子,我想在一个使用axios创建的服务函数中使用它,我用它来导出不同的方法。但是由于它不是一个函数或类组件我得到一个错误,react钩子必须在react函数组件或自定义react钩子函数中调用
useAxiosPrivate.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

我想在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,
     })

}

我得到一个错误,钩子应该用在顶层或者功能组件或类内部,我该怎么修复它?

t2a7ltrp

t2a7ltrp1#

您的服务也必须是一个挂接,这样它才能使用其他挂接

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,
      });
    },
  };
};

相关问题