简体   繁体   中英

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. 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

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

I want to use this in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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