0

I need ot use useSelector in a axios interceptor function to get user name. I have tryed to do in a custom hook but getting same error Any ideas how to do that?

currently Im getting:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

my code:

const instance: AxiosInstance = axios.create();

axiosInterceptor(instance);

function axiosInterceptor(instance: AxiosInstance): any {
  return instance.interceptors.request.use(
    (request) => axiosRequest(request),
    (error)   => axiosRequestError(error?.message, error)
  );
}

function axiosRequest(
  request: AxiosRequestConfig
): AxiosRequestConfig | Promise<AxiosRequestConfig> {
  const currentToken = useSelector(currentUserToken);

  request.headers["X-Auth-token"] = currentToken;
  return request;
}

function axiosRequestError(message: string, error?: any): Promise<any> {
  return Promise.reject(error || message);
}

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Arthur788
  • 11
  • 1
  • Does this answer your question? [Invalid hook call. Hooks can only be called inside of the body of a function component](https://stackoverflow.com/questions/56663785/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com) – technophyle Aug 14 '23 at 18:49
  • You need to create `useAxios` hook – Konrad Aug 14 '23 at 18:58
  • `useAxios` hook shoulld be entire `axiosInterceptor` function or a hook which returns `currentUserToken` ? – Arthur788 Aug 14 '23 at 19:57
  • It should return the axios instance – Konrad Aug 15 '23 at 01:37
  • what should return axios instance? Should axiosInterceptor change to hook or make a customer hook to get data from a `useSelector(currentUserToken)` ? – Arthur788 Aug 15 '23 at 09:47

0 Answers0